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

前端 未结 8 427
北恋
北恋 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: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, 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.

    提交回复
    热议问题