从方法返回继承的类型 [英] Return an inherited type from a method
问题描述
假设我定义了以下类:
Public Class BaseClass
...
End Class
Public Class DerivedClass
Inherits BaseClass
... Extra Fields, methods, etc ...
End Class
然后,在我的代码中,我有一个函数,其签名为:
And then, in my code, I have a function with a signature of:
Public Function DoSomething(...) As List(Of BaseClass)
当我尝试从中返回类型为List(Of DerivedClass)
的对象时,出现错误:
And when I try and return an object of type List(Of DerivedClass)
from it, I get the error:
Value of type 'System.Collections.Generic.List(Of BaseClass)' cannot be converted to 'System.Collections.Generic.List(Of DerivedClass)'
我不知道DerivedClass
的所有多余字段都将被填充,但是它将满足我的需要.
I know not all the extra fields of the DerivedClass
will be filled, but it would give me what I needed.
有没有办法做到这一点,或者这仅仅是不良的编程习惯?而且,如果是这样,正确的方法是什么?
Is there a way to do this, or is this just considered bad programming practice? And, if so, what would be the right way to do this?
推荐答案
看看这个:
http://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx
了解协方差和协方差会清除一些问题:)
Understanding Covariance and Contravariance will clear things up a bit :)
- 协方差
使您可以使用比最初指定的类型更具体的类型. 您可以将IEnumerable的实例(在Visual Basic中为IEnumerable(Of Derived))分配给IEnumerable类型的变量.
Enables you to use a more specific type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable.
示例:
IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;
- 矛盾性
- Contravariance
使您可以使用比最初指定的类型更为通用(派生较少)的类型. 您可以将IEnumerable的实例(在Visual Basic中为IEnumerable(Of Base))分配给IEnumerable类型的变量.
Enables you to use a more generic (less derived) type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable.
示例:
Action<Base> b = (target) => { Console.WriteLine(target.GetType().Name); };
Action<Derived> d = b;
d(new Derived());
- 不变性
- Invariance
意味着您只能使用最初指定的类型;因此,不变的泛型类型参数既不是协变也不是协变.您不能将IEnumerable的实例(在Visual Basic中为IEnumerable(Of Base))分配给IEnumerable类型的变量,反之亦然.
Means that you can use only the type originally specified; so an invariant generic type parameter is neither covariant nor contravariant. You cannot assign an instance of IEnumerable (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable or vice versa.
这篇关于从方法返回继承的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!