自引用界面

Com*_*r7G 7 c# xml interface

这是我想要做的事情:

Interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever)
}
Run Code Online (Sandbox Code Playgroud)

所以实现它的类必须有一个返回自己类型列表的函数.这甚至可能吗?我知道 - 技术上 - 实现这个的类可以返回实现它的其他类的列表,不一定是同一个类,但我可以忍受它,即使它不理想.

我试过这个,但我无法让实现类正确实现该方法.

Dan*_*rth 13

实现此接口是直截了当的:

public class MyInterfaceImpl : IMyInterface
{
    public List<IMyInterface> GetAll(string whatever)
    {
        return new List<IMyInterface> { new MyInterfaceImpl(), this };
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,方法签名必须完全相同,即返回类型必须是List<IMyInterface>和不是List<MyInterfaceImpl>.

如果希望列表中的类型与实现接口的类相同,则必须使用泛型:

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 };
    }
}
Run Code Online (Sandbox Code Playgroud)

  • [奇怪的重复模板模式]的好用例(http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern);) (3认同)

Dia*_*cus 1

这对我有用:

public interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever);
}

public class Program : IMyInterface
{
    public string Member { get; set; }

    public List<IMyInterface> GetAll(string whatever)
    {
        return new List<IMyInterface>()
            { new Program() { Member = whatever } };
    }

    static void Main(string[] args)
    {
        List<IMyInterface> all = new Program().GetAll("whatever");
        Console.WriteLine(all.Count);
    }
}
Run Code Online (Sandbox Code Playgroud)