2012-12-19 29 views
10

我有一個DisplayedData類...將一個類到一個數組

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; } } 
    } 

而且我希望把對象從該類到一個數組,其中該類內所有對象應轉換成字符串[]

我有..

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

,或者可以創建一個陣列,其中所有項的內部是由不同的數據的變量鍵入,以便整數仍然是一個整數,所以字符串呢?

+0

需要了解更多信息,提供一個很好的答案。有很多答案,你在這裏...你想收集用戶列表嗎?爲什麼一個String []? –

+1

你是否想要將每個屬性複製到字符串數組中?當你說「這個類中的所有對象應該被轉換成一個String []」時,你的意思是什麼,你只有類和整個類中的字符串,沒有意義將它們轉換爲字符串[],但是你可能想要複製到字符串[]。 – ryadavilli

+0

我想將這個類的所有公共int和字符串複製到一個數組中 –

回答

15

您可以創建一個數組 「用自己的手」(見Arrays Tutorial):

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

或者你可以使用Reflection (C# Programming Guide)

_chosenUser = _user.GetType() 
        .GetProperties() 
        .Select(p => 
         { 
          object value = p.GetValue(_user, null); 
          return value == null ? null : value.ToString(); 
         }) 
        .ToArray(); 
+0

非常感謝你:) –

相關問題