Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

c# - Self referencing interface

This is the kind of thing I want to do:

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

so that classes implementing this must have a function that returns a list of their own type. Is this even possible? I know that - technically - a class implementing this could return a list of other classes which implement this, not necessarily the same class, but I can live with that even though it isn't ideal.

I have tried this, but I can't get the implementing class to correctly implement the method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Implementing this interface is straight forward:

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

Please note that the method signature needs to be exactly the same, i.e. the return type has to be List<IMyInterface> and not List<MyInterfaceImpl>.

If you want the type in the list to be the same type as the class that implements the interface, you will have to use generics:

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 };
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...