我有一个方法将 IEnumerable
类型的对象作为输入参数.我想枚举枚举并为每个项目使用反射来获取每个属性的值。
我有以下代码:
protected void WriteData(IEnumerable data)
{
var enumerationTypeInfo = data.GetType();
var itemTypeInfo = enumerationTypeInfo.GetElementType();
...
}
问题是enumerationTypeInfo.GetElementType()
总是返回 null
.特别是,我传递了一个 List<Entry>
进入WriteData
, 其中Entry
是我创建的一个类。当我使用调试器并设置断点时,我可以看到 enumerationTypeInfo
正确显示它是 Entry
类型的列表,但为什么 GetElementType
返回 null
?
谢谢
最佳答案
GetElementType()
返回数组的元素类型。 List<T>
不是数组类型,因此没有“元素类型”。
如果要随机获取元素类型IEnumerable<T>
产生,尝试这样的事情:
public static Type GetEnumerableType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return type.GetGenericArguments()[0];
var iface = (from i in type.GetInterfaces()
where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)
select i).FirstOrDefault();
if (iface == null)
throw new ArgumentException("Does not represent an enumerable type.", "type");
return GetEnumerableType(iface);
}
请注意,类型可以实现同一通用接口(interface)的多个版本;一个类型可以同时实现 IEnumerable<int>
和 IEnumerable<string>
例如。你如何处理这种情况取决于你。我提供的方法将采用运行时首先交给它的接口(interface)类型。
参见 an example using the above method在 ideone 上。
关于c# - 为什么 Type.GetElementType 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7072088/