Self referencing interface

后端 未结 4 1957
眼角桃花
眼角桃花 2021-01-18 05:15

This is the kind of thing I want to do:

Interface IMyInterface
{
    List GetAll(string whatever)
}

so that classes imp

4条回答
  •  失恋的感觉
    2021-01-18 05:32

    Implementing this interface is straight forward:

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

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

    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 where T : IMyInterface
    {
        List GetAll(string whatever)
    }
    
    public class MyInterfaceImpl : IMyInterface
    {
        public List GetAll(string whatever)
        {
            return new List { new MyInterfaceImpl(), this };
        }
    }
    

提交回复
热议问题