C# 将泛型实例强制转换为基类

C# 将泛型实例强制转换为基类,c#,wpf,generics,C#,Wpf,Generics,我正在尝试一些事情,比如 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 { } vo

我正在尝试一些事情,比如

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
{

}
void Main()
{
临时测试=新的Foo();
}
抽象类Temp,其中T:Bar
{
}
类别Foo:Temp,其中T:Bar
{
}
抽象类栏
{
}
类InheritedBar:Bar
{
}
强制转换不起作用,错误为
无法将类型Foo隐式转换为Temp。

但是,,
Temp Test=new Foo()
Temp Test=new Foo()

两者都有效。为什么即使InheritedBar从Bar继承,它也不能通过泛型转换到它


我在wpf页面中使用泛型类型,不能将其创建为泛型,因此不能将t作为其类型传递。我只想要这个临时版本的功能,而不是任何派生版本的功能。有更好的方法吗?

您尝试使用的概念是协方差(关于的完整解释)

简而言之,您需要使用
out
标记您的通用参数;但您只能在接口上执行此操作(在您的案例中,从抽象类更改)。此外,根据方法参数和返回值,可能无法将接口标记为协变

interface Temp<out T> where T : Bar
{

}
接口温度,其中T:Bar
{
}
我不知道C#,但如果这是Java,这将是一个复制品。