Why can't I assign List to IEnumerable<object> in .NET 4.0

后端 未结 4 1467
慢半拍i
慢半拍i 2020-12-11 02:44

I try to do this:

IEnumerable ids = new List() { \"0001\", \"0002\", \"0003\" };


it works great!

But wh

相关标签:
4条回答
  • 2020-12-11 03:09

    int is a value type and can only be boxed to object - it doesn't inherit from object. Since you're using an IEnumerable<object> anyway, this should work:

    IEnumerable intIds = new List<int>() { 1, 2, 3 };
    
    0 讨论(0)
  • 2020-12-11 03:09

    Another solution would be to use the extension method Enumerable.Cast as such:

    Dim a as IEnumerable(Of Integer) = GetA()
    
    MethodThatTakesIEnumerableOfObject(a.Cast(Of Object))
    
    0 讨论(0)
  • 2020-12-11 03:12

    Simply put: generic variance in .NET 4 doesn't support variance for type arguments which are value types.

    The reason it can work for reference types is that once the CLR has decided it knows the generic conversion is safe, it can treat all reference values the same way - they have the same representation internally. No actual conversion is required to turn a string reference into an object reference, or vice versa if you know it's definitely a reference to a string - it's the same bits, basically. So the generated native code can just treat the references as references, happy in the knowledge that the rules around variance have guaranteed that nothing nasty will happen at the type safety level, and not performing any conversions on the values themselves.

    That isn't true for value types, or for reference types where the conversion isn't a "reference conversion" (i.e. a representation-preserving one). That's why you can't write IEnumerable<XName> names = new List<string>(); by the way...

    0 讨论(0)
  • 2020-12-11 03:12

    From MSDN Blogs > C# Frequently Asked Questions > Covariance and Contravariance FAQ:

    Variance is supported only if a type parameter is a reference type. Variance is not supported for value types. The following doesn’t compile either:

    // int is a value type, so the code doesn't compile.
    IEnumerable<Object> objects = new List<int>(); // Compiler error here.
    
    0 讨论(0)
提交回复
热议问题