C# 泛型类型参数上多个约束的优先级
在下面的示例中,我对泛型类C# 泛型类型参数上多个约束的优先级,c#,generics,type-constraints,C#,Generics,Type Constraints,在下面的示例中,我对泛型类FoobarList中的类型T有两个约束,Foobar和IFoobar。但编译器给出了一个错误:无法将类型“Foobar”隐式转换为“T”。存在显式转换(是否缺少强制转换?) 接口IFoobar { T CreateFoobar(); } 类Foobar:IFoobar { //一些食物 public Foobar CreateFoobar(){返回新的Foobar();} } 类FoobarList,其中T:Foobar,IFoobar { 空隙试验(T rFooba
FoobarList
中的类型T有两个约束,Foobar
和IFoobar
。但编译器给出了一个错误:无法将类型“Foobar”隐式转换为“T”。存在显式转换(是否缺少强制转换?)
接口IFoobar
{
T CreateFoobar();
}
类Foobar:IFoobar
{
//一些食物
public Foobar CreateFoobar(){返回新的Foobar();}
}
类FoobarList,其中T:Foobar,IFoobar
{
空隙试验(T rFoobar)
{
T foobar=rFoobar.CreateFoobar();//错误:无法将foobar转换为T
}
}
编译器似乎认为CreateFoobar是Foobar中的一个方法,而不是IFoobar中的方法。我可以通过将Foobar划分为基类FoobarBase并在其派生类中实现接口IFoobar来修复编译,如下所示:
interface IFoobar<T>
{
T CreateFoobar();
}
abstract class FoobarBase
{
//some foobar stuffs
}
class Foobar : FoobarBase, IFoobar<Foobar>
{
public Foobar CreateFoobar() { return new Foobar(); }
}
class FoobarList<T> where T : FoobarBase, IFoobar<T>
{
void Test(T rFoobar)
{
T foobar = rFoobar.CreateFoobar();
}
}
接口IFoobar
{
T CreateFoobar();
}
抽象类foobase
{
//一些食物
}
Foobar类:FoobarBase,IFoobar
{
public Foobar CreateFoobar(){返回新的Foobar();}
}
类FoobarList,其中T:FoobarBase,IFoobar
{
空隙试验(T rFoobar)
{
T foobar=rFoobar.CreateFoobar();
}
}
将Foobar划分为两个类很麻烦。有更好的方法解决这个问题吗?只需将
rFoobar
转换为IFoobar
:
这样,在
t
中找不到该方法,因此它将再次解析为接口方法。实现接口是否有明确的帮助?
interface IFoobar<T>
{
T CreateFoobar();
}
abstract class FoobarBase
{
//some foobar stuffs
}
class Foobar : FoobarBase, IFoobar<Foobar>
{
public Foobar CreateFoobar() { return new Foobar(); }
}
class FoobarList<T> where T : FoobarBase, IFoobar<T>
{
void Test(T rFoobar)
{
T foobar = rFoobar.CreateFoobar();
}
}
T foobar = ((IFoobar<T>)rFoobar).CreateFoobar();
Foobar IFoobar<Foobar>.CreateFoobar() { return new Foobar(); }