Convert a class into an array

2019-06-16 01:58发布

I have a DisplayedData class ...

  public class DisplayedData
  {
    private int _key;
    private String _username;
    private String _fullName;
    private string _activated;
    private string _suspended;


    public int key { get { return _key; } set { _key = value; } }
    public string username { get { return _username; } set { _username = value; } }
    public string fullname { get { return _fullName; } set { _fullName = value; } }
    public string activated { get { return _activated; } set { _activated = value; } }
    public string suspended { get { return _suspended; } set { _suspended = value; } }
  }

And I want to to put the objects from this class into an array where all objects inside of this class should be converted into an String[]

I have..

DisplayedData _user = new DisplayedData();
String[] _chosenUser = _user. /* Im stuck here :)

or can I create an array where all the items inside are consist of variables of different datatype so that the integer remains an integer and so the strings too?

标签: c# arrays class
1条回答
Emotional °昔
2楼-- · 2019-06-16 02:22

You can create an array "with your own hands" (see Arrays Tutorial):

String[] _chosenUser = new string[] 
{ 
    _user.key.ToString(), 
    _user.fullname,
    _user.username,
    _user.activated,
    _user.suspended
};

Or you could use Reflection (C# Programming Guide):

_chosenUser = _user.GetType()
                    .GetProperties()
                    .Select(p =>
                        {
                            object value = p.GetValue(_user, null);
                            return value == null ? null : value.ToString();
                        })
                    .ToArray();
查看更多
登录 后发表回答