Using List <interface> in another C # interface

I am trying to create an interface for a model class in ASP.NET MVC2, and I am wondering if I can use List<interface> in another interface. It is better if I give a code example.

I have two interfaces, the terminal can have several compartments. Therefore, I code my interfaces as follows.

Bay Interface:

 public interface IBay { // Properties int id {get; set;} string name {get;set;} // ... other properties } 

Terminal interface:

 public interface ITerminal { // Properties int id {get;set;} string name {get;set;} // ... other properties List<IBay> bays {get;set;} } 

My question is, when I implement my class based on these interfaces, how to set up a list of compartments. Should I make a list of compartments outside the ITerminal interface and inside a specific implementation?

My goal is to do the following:

Specific implementation:
Bay Class:

 class Bay : IBay { // Constructor public Bay() { // ... constructor } } 

Terminal Class:

 class Terminal : ITerminal { // Constructor public Terminal() { // ... constructor } } 

And then access the list of fills like this

 Terminal.Bays 

Any help / suggestions would be greatly appreciated.

+4
source share
2 answers

This should work fine. Just understand that your Terminal class will still contain a List<IBay> , which can be populated with Bay instances as needed. (Note that I would recommend using IList<IBay> .)

If you want the terminal to return specific Bay types, you will need to reconfigure your terminal interface and change it as:

 public interface ITerminal<T> where T : IBay { // Properties int Id {get;set;} string Name {get;set;} IList<T> Bays {get;} } public Terminal : ITerminal<Bay> { private List<Bay> bays = new List<Bay>(); IList<Bay> Bays { get { return bays; } } // ... public Terminal() { bays.Add(new Bay { //... 

However, adding this complexity can make little sense.

+4
source

You can initialize the list-interface by filling it with specific instances. For example, to initialize the Terminal class using collection objects and initializers , you can use code similar to:

 Terminal terminal = new Terminal { id = 0, name = "My terminal", bays = new List<IBay> { new Bay { id = 1, name = "First bay" }, new Bay { id = 2, name = "Second bay" }, new Bay { id = 3, name = "Third bay" }, } }; 

Some points of your code:

  • By convention, all public properties must be PascalCased. Use Id or Id instead of Id ; Name instead of Name ; Bays instead of Bays .
  • Since you pay so much attention to interfaces, you should consider changing the type of the Bays property from List<IBay> to IList<IBay> . This will allow consumers to assign IBay[] arrays to it.
+6
source

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


All Articles