Reflection, Casting List to IEnumerable<object>

后端 未结 1 1517
日久生厌
日久生厌 2021-01-20 16:24

I have a class that i need to reflect through an object properties and check values and other things. Everything seems to be working exception when i have a list and try to

1条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-20 17:14

    The fact that int is a value type makes the difference here. According to C# spec there must be a reference or identity conversion between generic types to make types variant-convertible:

    A type T is variance-convertible to a type T if T is either an interface or a delegate type declared with the variant type parameters T, 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 is covariant, so the line I marked is important. Ai in your case is int and Bi is int. There is no reference conversion from int to object, because int is not a reference type. There is also no identity conversion between these two, because they are not the same.

    I don't know the entire context of your question, but you can use non-generic IEnumerable instead of IEnumerable. They are pretty much the same. However, you might be facing an XY problem here, so it's hard to help you without knowing more about your case.

    0 讨论(0)
    提交回复
    热议问题