这是我想做的事情:
Interface IMyInterface
{
List<IMyInterface> GetAll(string whatever)
}
因此实现它的类必须有一个返回它们自己类型的列表的函数。 这可能吗? 我知道 - 从技术上讲 - 一个实现它的类可以返回一个实现它的其他类的列表,不一定是同一个类,但我可以接受它,即使它并不理想。
我已经试过了,但是我无法让实现类正确地实现这个方法。
最佳答案
实现这个接口(interface)很简单:
public class MyInterfaceImpl : IMyInterface
{
public List<IMyInterface> GetAll(string whatever)
{
return new List<IMyInterface> { new MyInterfaceImpl(), this };
}
}
请注意,方法签名需要完全相同,即返回类型必须是 List<IMyInterface>
而不是 List<MyInterfaceImpl>
.
如果希望列表中的类型与实现接口(interface)的类的类型相同,则必须使用泛型:
public interface IMyInterface<T> where T : IMyInterface<T>
{
List<T> GetAll(string whatever)
}
public class MyInterfaceImpl : IMyInterface<MyInterfaceImpl>
{
public List<MyInterfaceImpl> GetAll(string whatever)
{
return new List<MyInterfaceImpl > { new MyInterfaceImpl(), this };
}
}
关于c# - 自引用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16935957/