当我不知道它的确切类型时,如何测试类成员是否是列表?然后我如何迭代它呢?
myc是MyClass的一个实例
using System.Reflection;
public class MyClass {
public sometype somename { get; set; }
public List<double> doubles { get; set; }
public List<string> strings { get; set; }
}
foreach(PropertyInfo pi in MyClass.GetProperties()) {
if (pi.GetValue(myc, null) is List<???>){ <--- what should this be?
foreach(object obj in pi.GetValue(myc, null)) { <---- doesn't work
}
var l = pi.GetValue(myc, null) as List<???> <---- doesn't work
}
}
Run Code Online (Sandbox Code Playgroud)
如果您要做的只是枚举值,则可以测试非泛型IEnumerable:
object value = pi.GetValue(myc, null);
IEnumerable enumerable = value as IEnumerable;
if (enumerable != null)
{
foreach (object obj in enumerable)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这将迭代字符串中的字符,如string实现IEnumerable<char>.你可能想要硬编码.
如果你很高兴与任何IList实现(包括List<T>),你可以代替IList的IEnumerable上面.
请注意,基本上这是避免进入泛型 - 在反射中检测和使用泛型是一件混乱的事情.