c# - 自引用接口(interface)

标签 c# xml interface

这是我想做的事情:

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/

相关文章:

java - 静态 final 列表的接口(interface)或类?

c# - asp.net Entity Framework <%# Bind ("linkedTable.Field") %>

c# - 扩展类以符合接口(interface)?

c# - DataGridView 中没有重复项

xml - 用 map 解析Grails中的response.xml

java - 删除 BottomNavigationView 图标和中心标题

java - 如何修改log4j中的map lookup

java - 代表们——如何做?

c# - 如何将函数或字符串存储为字典中的值 (C#)

c# - HttpWebRequest 如何处理(过早)关闭底层 TCP 连接?