如果属性是任何类型的列表,则获取C#

Dan*_*cco 0 c# reflection list

我正在尝试根据我的类属性以下列模式创建一个文本编写器:

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; }
}
Run Code Online (Sandbox Code Playgroud)

所以我拿每个属性名称,写它,一个空格,然后是它的值(如果有的话).现在我正在尝试实现对列表和类似数组的支持,如下所示:

MyClass
    ArrayTest
        1
        2
        3
Run Code Online (Sandbox Code Playgroud)

如果它是一个类,我将对该函数进行递归,这样我就可以在这个模式中显示列表/数组中的所有值.(这是一个网络服务)

我的问题是,我怎样才能找到特定属性是否可以列表?

我试过了:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Bas*_*Bas 6

就像评论中提到的那样:使用Json作为格式化对象的方式,它将节省大量时间.

如果您有理由不这样做,可以检查类型是否可枚举:这也包括Type.IsArray案例.

typeof(IEnumerable).IsAssignableFrom(properties[i].PropertyType)
Run Code Online (Sandbox Code Playgroud)

作为一个警告的补充通知:也许你不想枚举Stringbyte[]输入对象.