我试图尝试诸如此类的东西
void Main() { Temp<Bar> Test = new Foo<InheritedBar>(); } abstract class Temp<T> where T : Bar { } class Foo<T> : Temp<T> where T : Bar { } abstract class Bar { } class InheritedBar : Bar { }Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.不起作用,错误Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.
但是, Temp<InheritedBar> Test = new Foo<InheritedBar>(); 和Temp<Bar> Test = new Foo<Bar>();
两者都有效。 为什么即使InheritedBar继承自Bar,它也不能通过泛型强制转换为它?
我在wpf页面中使用泛型类型,它不能创建为泛型,因此我不能将T作为其类型传递。 我只想要Temp的这个功能,而不是任何派生版本的功能。 有一个更好的方法吗?
I am trying to attempt something such as
void Main() { Temp<Bar> Test = new Foo<InheritedBar>(); } abstract class Temp<T> where T : Bar { } class Foo<T> : Temp<T> where T : Bar { } abstract class Bar { } class InheritedBar : Bar { }The cast does not work, with the error Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.
However, Temp<InheritedBar> Test = new Foo<InheritedBar>(); and Temp<Bar> Test = new Foo<Bar>();
Both work. Why even though InheritedBar inherits from Bar, it can't be cast to it through generics?
I am using the generic type in a wpf Page, which can not be created as a generic so I can't pass T as its type. I only want the functionality at the time of this of Temp, not any of the derived versions functionality. Is there a better way to do this?
最满意答案
您尝试使用的概念是协方差 ( MSDN上的完整说明)
简短的回答是你需要使用标记你的泛型参数; 但是你只能在一个接口上做到这一点(在你的情况下从一个抽象类改变)。 此外,根据您的方法参数和返回值,您可能无法将您的界面标记为协变。
interface Temp<out T> where T : Bar { }The concept you are attempting to utilize is covariance (full explanation on MSDN)
The short answer is that you need to use mark your generic parameter with out; but you can only do that on an interface (changing from an abstract class in your case). Also, depending on your method parameters and return values, you may not be able to mark your interface as covariant.
interface Temp<out T> where T : Bar { }更多推荐
发布评论