2014-07-15 36 views
0

我努力使根據我的課在下面的模式屬性文本編寫的:C#得到一個屬性是任何類型的列表

MyClass 
    ID 1 
    Name MyName 
    AnotherProperty SomeValue 
    ThisIsAnotherClass 
     AnotherClassProperties 1 

//Example class 
public class MyClass 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string AnotherProperty { get; set; } 
    public AnotherClass ThisIsAnotherClass { get; set; } 
} 

所以我採取每個屬性的名稱,它寫,一個空格,那麼它是價值(如果有的話)。 現在我想實現這樣的事情列表和任何類似數組的支持:

MyClass 
    ArrayTest 
     1 
     2 
     3 

如果它是一個類,我將有功能的遞歸這樣我就可以顯示裏面的所有值列表/數組在這種模式。 (這是一個web服務)

我的問題是,我怎麼能找到一個特定的屬性是列表能夠?

我已經試過:在評論中提到

Type type = myObject.GetType(); 
PropertyInfo[] properties = type.GetProperties(); 
for(int i = 0; i < properties.Length; i++) 
{ 
    if(properties[i].PropertyType.IsGeneric) //Possible List/Collection/Dictionary 
    { 
     //Here is my issue 
     Type subType = properties[i].PropertyType.GetGenericTypeDefinition(); 
     bool isAssignable = subType.IsAssignableFrom(typeof(ICollection<>)); //Always false 
     bool isSubclass = subType.IsSubclassOf(typeof(ICollection<>)); //Always false 

     //How can I figure if it inherits ICollection/IEnumerable so I can use it's interface to loop through it's elements? 
    } 
    else if(properties[i].PropertyType.IsArray) //Array 
    { 
    } 
    else if(properties[i].PropertyType.IsClass && !properties[i].PropertyType.Equals(typeof(String))) 
    { 
     //Non-string Subclasses, recursive here 
    } 
    else 
    { 
     //Value types, write the text + value 
    } 
} 
+4

爲什麼不只是使用JSON,它已經有一個解析器,並沒有引入更多的噪音。 –

+0

IsAssignableFrom幾乎總是與常識相反。你問是否可以從你的類型分配接口,而不是相反。 –

+0

@DavinTryon我對JSON瞭解不多,但我不認爲你可以編輯它如何格式化數據的權利?在這種情況下,客戶希望以非常煩人/特定的方式接收數據,這就是爲什麼我要爲此做類。 – Danicco

回答

6

像:使用JSON作爲一種格式化的對象,這將節省大量的時間。

如果您有理由不這樣做,您可以檢查類型是否可枚舉:這也涵蓋了Type.IsArray的情況。

typeof(IEnumerable).IsAssignableFrom(properties[i].PropertyType) 

作爲謹慎的一個額外的通知:也許你不想列舉Stringbyte[]類型的對象。

相關問題