gpt4 book ai didi

c# - 反射,将 List 转换为 IEnumerable
转载 作者:行者123 更新时间:2023-11-30 14:55:21 25 4
gpt4 key购买 nike

我有一个类,我需要通过对象属性来反射(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 type T<B1, …, Bn> if T is either an interface or a delegate type declared with the variant type parameters T<X1, …, Xn>, and for each variant type parameter Xi one of the following holds:

  • Xi is covariant and an implicit reference or identity conversion exists from Ai to Bi
  • Xi is contravariant and an implicit reference or identity conversion exists from Bi to Ai
  • Xi is invariant and an identity conversion exists from Ai to Bi

IEnumerable<T>是协变的,所以我标记的那一行很重要。 Ai在你的情况下是 intBiint . int 没有引用转换至 object ,因为 int不是引用类型。这两者之间也不存在身份转换,因为它们不相同。

我不知道你问题的全部背景,但你可以使用非通用的 IEnumerable而不是 IEnumerable<object> .它们几乎相同。但是,您在这里可能会遇到 XY 问题,因此在不了解您的案例的情况下很难为您提供帮助。

关于c# - 反射,将 List<Int32> 转换为 IEnumerable<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25479778/

25 4 0