7

这是我想做的事情:

Interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever)
}

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

我已经尝试过了,但我无法让实现类正确实现该方法。

4

4 回答 4

13

实现这个接口很简单:

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

请注意,方法签名需要完全相同,即返回类型必须是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 };
    }
}
于 2013-06-05T09:18:56.830 回答
2

这是一个正常的解决方案。考虑你有接口IPerson并且你想访问一个人的每个父母。所以接口声明如下是合理的:

interface IPerson
{
    IList<IPerson> GetAllParents();
}

现在你可以得到那个父母的父母,然后得到父母......希望你明白了。这种设计非常灵活,因为它允许使用简单的静态模型对深层动态结构进行建模。

实现非常简单:

class Person : IPerson
{
    IList<IPerson> parents;

    public Person(IList<IPerson> parents)
    {
        this.parents = parents;
    }

    public IList<IPerson> GetAllParents()
    {
        return parents;
    }
}

从某种意义上说,您需要创建一些没有父母的人(某种亚当和夏娃),然后通过引用他们的父母来添加孩子。如您所见,我的幼稚模型可以处理随机的深层家庭结构,同时具有非常简单的暴露在外部的接口。

于 2013-06-05T09:19:51.310 回答
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);
    }
}
于 2013-06-05T09:30:33.540 回答
1

我不明白为什么接口不能引用自身——下面没有问题。

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

class MyClass : ITest
{
    public List<ITest> GetAll(string whatever)
    {
        return new List<ITest>();
    }
}
于 2013-06-05T09:20:47.690 回答