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

前端 未结 8 422
北恋
北恋 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 customers = new List(); //ok, seems fair
    List objects = new List(); // 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 to a List 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.

    提交回复
    热议问题