我正在创建一个接口,我需要一个方法来引用实现该接口的类的类实例。这是一个例子:
class MyClass : IMyInterface{
public void MyMethod(MyClass a){...} //implemented from the interface.
}
那么我应该如何实现我的界面(没有泛型)来引用它实现的类?
interface IMyInterface{
void MyMethod(??? a);
}
???
部分会有什么结果?
谢谢, 可以。
答案 0 :(得分:9)
C#类型系统不够复杂,不足以代表“自我”类型的概念。 IMO,理想的解决方案是放弃这个目标,只依赖于接口类型:
interface IMyInterface
{
void MyMethod(IMyInterface a);
}
如果这个不足,通常暗示接口指定不当;如果可能的话,你应该回到绘图板并寻找替代设计。
但如果你仍然 需要这个,你可以使用CRTP的(某种)C#版本:
interface IMyInterface<TSelf> where TSelf : IMyInterface<TSelf>
{
void MyMethod(TSelf a);
}
然后:
class MyClass : IMyInterface<MyClass>
{
public void MyMethod(MyClass a) {...} //implemented from the interface.
}
请注意,这不是一个完全“安全”的解决方案;没有什么能阻止邪恶的实现使用不同的类型参数:
class EvilClass : IMyInterface<MyClass> // TSelf isn't the implementing type anymore...
{
public void MyMethod(MyClass a) {...} // Evil...
}
违背您的目标。
答案 1 :(得分:0)
只需使用IMyInterface
代替MyClass
。它将能够接受从该接口派生和使用的任何内容。如果由于某种原因你不想这样做,仍然会这样做,但是在界面上添加一些其他的“检查”,比如public bool IsValidParam()
或其他什么。一般来说,我会考虑这样糟糕的设计(接口不应该依赖于实际接口的任何实现,除了接口本身提供的东西)。