Dam*_*ury 0 c# generics inheritance interface constraints
假设我有一个接口IA,包含一个名为Foo的泛型方法.
public interface IA {
int Foo<T>(T otherType);
}
Run Code Online (Sandbox Code Playgroud)
我希望T与派生类的类型相同:
class A : IA {
int Foo(A otherType)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我试过以下(语法错误):
public interface IA {
int Foo<T>(T otherType) where T : this;
}
Run Code Online (Sandbox Code Playgroud)
我的约束如何才能实现这一目标?
你必须这样做:
public interface IA<T>
{
int Foo(T otherType);
}
class A : IA<A>
{
public int Foo(A otherType)
{
return 42;
}
}
Run Code Online (Sandbox Code Playgroud)
这是强制执行接口成员泛型类型的唯一方法.