简体   繁体   English

从PropertyInfo检索未知类型的列表

[英]Retrieve List of unknown type from PropertyInfo

I have a class with a list defined. 我有一个带有已定义列表的类。

class Program
{          
      public List<string> list { get; set; }
};

I need to retrieve this list using PropertyInfo , but the issue is that the List can be of any type (here string). 我需要使用PropertyInfo检索此列表,但问题是该列表可以是任何类型(此处为字符串)。 How do I extract the values of the list using propertyinfo as getValue() doesn't return me a list. 我如何使用propertyinfo作为getValue()提取列表的值不会返回列表。

You can cast it to IList then use a loop: 您可以将其IListIList然后使用循环:

var myList = (IList)typeof(Program)
                    .GetProperty("list")
                    .GetValue(yourInstance);

If you don't know the actual type of your list, that's all you can do.If you know the type at compile-time , then you can cast it to IList<T> 如果您不知道列表的实际类型,就可以这样做。如果您在编译时知道该类型,则可以将其IList<T>IList<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM