Why can't I pass List as a parameter to a method that accepts List<object>?

前端 未结 8 424
北恋
北恋 2021-01-11 13:31

The following code gives me this error:

Cannot convert from \'System.Collections.Generic.List\' to \'System.Collections.Generic.List\'.

相关标签:
8条回答
  • 2021-01-11 14:06

    This has been covered ad-nauseum in many other answers. The short answer is this:

    Consider I have these variables:

    List<Customer> customers = new List<Customer>(); //ok, seems fair
    List<object> objects = new List<object>(); // again, everything's fine
    

    Now, here's where it stops compiling:

    objects = customers; // sounds OK, since a Customer is an object, right?
    
    objects.Add("foo"); 
    

    Does that make sense now?

    C# 4.0 will introduce limited ability to do what you're attempting, though being able to do exactly as you describe (assign a List<Customer> to a List<object> won't be allowed for the same reasoning I outlined above). See Eric Lippert's blog for more information, and a correction to some misinformation that's going around the interwebs.

    To address your comment above, there's no reason that you can't perform the same reflection operations on a Customer instance as you can on an object.

    0 讨论(0)
  • 2021-01-11 14:09

    That's the problem of covariance, and it is not as easy as it looks at first sight. C# 4 will have some support for that.

    To get the idea of the problems, imagine in your case that this cast would actually work. Now you'h have a List<object>, which for instance also has an Add method. However, the argument for the actual Add must be a Customer, so that this clearly violates the implementation; the implementation does not provide the Add(object obj) method.

    Unfortunately, some issues could have been solved by using a smart(er) design of the interfaces with generic methods where covariance is OK, such as for GetEnumerator.

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