我有一个类,我需要通过对象属性来反射(reflect)并检查值和其他东西。当我有一个列表并尝试将项目转换为 IEnumerable 时,一切似乎都正常工作。
if (propType.GetInterfaces().Contains(typeof(IEnumerable)))
{
var value = prop.GetValue(source);
Type underlyingType = propType.GetGenericArguments()[0];
var enumerable = value as IEnumerable<object>;
if(enumerable == null)
{
// problem here......
}
// Check the items in the list
}
propType 返回为:
FullName = "System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
底层类型返回为:
System.Int32
当它是一个自定义类的列表时,这是可行的,当它是一个值类型时,它似乎就被打破了。
有人可以帮忙吗?
最佳答案
事实int
是值类型在这里有所不同。根据 C# 规范,泛型类型之间必须有引用或标识转换才能使类型变体可转换:
A type
T<A1, …, An>
is variance-convertible to a typeT<B1, …, Bn>
ifT
is either an interface or a delegate type declared with the variant type parametersT<X1, …, Xn>
, and for each variant type parameterXi
one of the following holds:
Xi
is covariant and an implicit reference or identity conversion exists fromAi
toBi
Xi
is contravariant and an implicit reference or identity conversion exists fromBi
toAi
Xi
is invariant and an identity conversion exists fromAi
toBi
IEnumerable<T>
是协变的,所以我标记的那一行很重要。 Ai
在你的情况下是 int
和 Bi
是int
. int
没有引用转换至 object
,因为 int
不是引用类型。这两者之间也不存在身份转换,因为它们不相同。
我不知道你问题的全部背景,但你可以使用非通用的 IEnumerable
而不是 IEnumerable<object>
.它们几乎相同。但是,您在这里可能会遇到 XY 问题,因此在不了解您的案例的情况下很难为您提供帮助。
关于c# - 反射,将 List<Int32> 转换为 IEnumerable<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25479778/