开发者

Why aren't classes in .NET 4 covariant? [duplicate]

开发者 https://www.devze.com 2023-01-01 20:20 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Why isn’t there generic variance for classes in C# 4.0?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why isn’t there generic variance for classes in C# 4.0?

As a rookie programmer I have a couple of questions about variance in .NET 4. Not so much about how it works, but why certain things are not variant and if other people would find this useful.

Question 1:

I know that interfaces and delegates can be covariant/contravariant in .NET 4, but why not classes? So, question 1:

List(of BaseClass) = List(of DerivedClass)

Is this somehow unsafe? Wouldn't this be useful?


Question 2:

Question 2 follows from question 1, but may deal more with signatures than variance. Suppose I have a MustInherit class with a MustOverride member:

Public Must开发者_如何学GoInherit Class TestBase
    Public MustOverride Property SomeClass as BaseClass
End Class

In the derived class, why can't I override SomeClass and return a Derived Class Of BaseClass? Is this unsafe? Is it just that the signatures don't check for inheritance relationships?

Public Class TestSpecific
    Inherits TestBase
    Public Overrides Property SomeClass as DerivedClass
End Class

Any insight as to why this isn't allowed in .NET 4 would be appreciated.


Eric Lippert answers the first part of you question here.

As for the second part of you question, return type covariance has been requested for both C# and VB.NET - however it has not yet been prioritized high-enough relative to other language features to make it into any release. If I remember correctly, this feature would also require changes to the CLR to be implemented appropriately.

As to why this is so, I'll channel Eric Lippert for a moment and respond that not implementing a feature is free, while implementing a features requires the budget and time to design, develop, test, and document it ... which is not free. A feature has to be sufficiently valuable to enough people to justify the expense of creating it.

0

精彩评论

暂无评论...
验证码 换一张
取 消