![](/img/trans.png)
[英]How detect is a method in a C# class is implementing a method from an interface?
[英]How to reference the implementing class from an interface?
我正在創建一個接口,在這里我需要一個方法來引用實現該接口的類的類實例。 這是一個例子:
class MyClass : IMyInterface{
public void MyMethod(MyClass a){...} //implemented from the interface.
}
那么我應該如何實現我的接口(沒有泛型)來引用實現它的類呢?
interface IMyInterface{
void MyMethod(??? a);
}
會發生什么???
部分?
謝謝,可以。
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...
}
這違反了您的目標。
只需使用IMyInterface
而不是MyClass
。 它將能夠接受從該接口派生並使用該接口的任何內容。 如果您出於某種原因不希望這樣做,仍然可以這樣做,但是可以在接口上添加其他“檢查”,例如public bool IsValidParam()
東西。 總的來說,我會考慮類似這樣的不良設計(除了接口本身提供的內容外,接口不應依賴於實際接口的任何實現)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.