2017-01-04 186 views
1

我想尝试一些诸如投泛型实例基类

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>.

然而, Temp<InheritedBar> Test = new Foo<InheritedBar>();Temp<Bar> Test = new Foo<Bar>();

两者都有效。为什么尽管InheritedBar继承自Bar,它不能通过泛型转换为它?

我在wpf Page中使用泛型类型,它不能作为泛型创建,因此我无法将T作为其类型传递。我只想在Temp的时候这个功能,而不是任何派生版本的功能。有一个更好的方法吗?

+0

我不知道C#,但如果这是Java的,这将是[这个问题]的欺骗(http://stackoverflow.com/q/2745265/5743988)。 – 4castle

回答

3

你正试图利用这个概念是协方差(上MSDN完整说明)

简短的回答是,你需要使用带有out标记您的泛型参数;但你只能在界面上做到这一点(从你的案例中的抽象类更改)。另外,根据您的方法参数和返回值,您可能无法将界面标记为协变。

interface Temp<out T> where T : Bar 
{ 

}