C #: interface for formatting a list of elements inheriting an interface

I have the following interface:

IMyInterface
{
     IList<IMyInterface> MyList { get; set; }
     int X { get; set; }
     int Y { get; set; }
}

I want to force a class that implements this interface to have a list of "MyList" with a list of other elements that also implement IMyInterface. How to do it?

I get errors if I try the following:

public class MyClass: IMyInterface
{
    public int X { get; set; }
    public int Y { get; set; }
    public List<MyClass> MyList { get; set; }
}
+4
source share
3 answers

If you want the elements MyListto belong to the class of the implementing type, you need to use generics. You should also use restraint to make you Tbe the type that implements the interface. And MyListstill should be IListin the implementation class.

IMyInterface<T> where T : IMyInterface<T>
{
     IList<T> MyList { get; set; }
     int X { get; set; }
     int Y { get; set; }
}

public class MyClass: IMyInterface<MyClass>
{
    public int X { get; set; }
    public int Y { get; set; }
    public IList<MyClass> MyList { get; set; }
}

This does not stop someone from doing something like

public class AnotherClass: IMyInterface<MyClass>
{
    public int X { get; set; }
    public int Y { get; set; }
    public IList<MyClass> MyList { get; set; }
}

.

+4
public interface IMyInterface<T>
{
    IList<T> MyList { get; set; }
    int X { get; set; }
    int Y { get; set; }
}
public class MyClass : IMyInterface<MyClass>
{
    public int X { get; set; }
    public int Y { get; set; }
    public IList<MyClass> MyList { get; set; }
}

- :

public interface IMyInterface<T>
{
    List<T> MyList { get; }
    int X { get; set; }
    int Y { get; set; }
}
public class MyClass : IMyInterface<MyClass>
{
    public int X { get; set; }
    public int Y { get; set; }
    public List<MyClass> MyList { get; }
}

, setter MyList, , MyClass.

+1

Other answers are what you want, but still you cannot force the user to do. You only force the user to implement the IMyInterface injection class, and I can still do

public interface IMyInterface<T> where T : IMyInterface<T>
{
    IList<T> MyList { get; set; }
    int X { get; set; }
    int Y { get; set; }
}

public class MyClass : IMyInterface<MyClass>
{
    public int X { get; set; }
    public int Y { get; set; }
    public IList<MyClass> MyList { get; set; }
}

public class FooBar : IMyInterface<MyClass>
{
    public IList<MyClass> MyList { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
}

It FooBarsatisfies all the rules, still MyListhas a type IList<MyClass>, but not a type ILIst<FooBar>.

0
source

Source: https://habr.com/ru/post/1675615/


All Articles