c# - 反射,将 List<Int32> 转换为 IEnumerable<object>

标签 c# .net

我有一个类,我需要通过对象属性来反射(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/

相关文章:

c# - 为什么 C# 编译器不能告诉这个函数总是返回或抛出?

c# - 如果虚方法被声明为抽象的

c# - 在 C# 中,为什么从 List 创建 HashSet 比从 HashSet 开始更快?

.net - Powershell - 更改环境变量的值

c# - 如何使用 MVVM 在 WPF 的主窗口中显示用户控件

c# - MVC 在后 ActionResult 中获取表单控件数据属性值

C#,结构与类,更快?

c# - 结合秒表和计时器,通过平滑强制获得长期准确的事件

c# - "InvalidOperationException: No service for type ' Microsoft.Extensions.Configuration.IConfiguration ' has been registered."

c# - WCF 点对点,那里有节点吗?