[英]C# - Interface generic method constraint to match derived type
Let's say I have an interface IA, containing a generic method called Foo. 假设我有一个接口IA,其中包含一个称为Foo的通用方法。
public interface IA {
int Foo<T>(T otherType);
}
I want T to be the same type as the derived class: 我希望T与派生类具有相同的类型:
class A : IA {
int Foo(A otherType)
{
}
}
I tried following (syntax error): 我尝试了以下操作(语法错误):
public interface IA {
int Foo<T>(T otherType) where T : this;
}
How does my constraint need to look like to achieve that? 我的约束看起来如何实现这一目标?
You would have to do it like this: 您必须这样做:
public interface IA<T>
{
int Foo(T otherType);
}
class A : IA<A>
{
public int Foo(A otherType)
{
return 42;
}
}
It's the only way to enforce the interface member's generic type. 这是强制接口成员的泛型类型的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.