简体   繁体   中英

How can I create a list with Interface Instances

I have an interface:

public Interface IStudent
{
    Students students {get;}
    Boolean CanStayAfterHours;
}

public enum Students
{
    Student1,
    Student2,
    Student3,
    Student4
}

How can I add IStudent properties to a generic list? List<IStudent> ?

You first need to have a class that implements that interface:

public class Student : IStudent {
    Students students { get; set; } // set, for example
    Boolean CanStayAfterHours { get; set; }
}

Then you can add them to a list like this:

var studentList = new List<IStudent>() {
    new Student() { CanStayAfterHours = true },
    new Student() { CanStayAfterHours = false, Students = Students.Student1 },
    new Student() { CanStayAfterHours = true },
};

Your design doesn't make much sense... but I'll leave that to you to figure out.

IList<IStudent> can be used to keep a list of IStudent objects. Of course you need a class Student that implements IStudent , because you cannot create an instance of an interface. The purpose of your enum is unclear, you clearly don't want an enum value for each student, since that would require a rebuild of your application every time a new student signs up.

You'll need to implement a concrete object that implements the interface

public class ConcreteStudent : IStudent {

public Students students { get; set; }
public bool CanStayAfterHours { get; set; }

}

Some changes where required to the interface, I added some setters to the interface, hope this agrees with your design

public interface IStudent {

    Students students { get; set; }
    Boolean CanStayAfterHours { get; set; }

}

Then adding these objects to a list, we do the following

List<IStudent> students = new List<IStudent>()
students.Add(new ConcreteStudent()
{
 students = Students.Student1,

});

interface ListofPatientService { List

  retriev();

}
class listofServiceDummy : ListofPatientService
{
    List<patientmodel> list = new List<patientmodel>
    {
         new patientmodel(){Name="Abdi", Age= 30, Description=""},
         new patientmodel(){Name="HassaN", Age= 40, Description=""},
          new patientmodel(){Name="Hasna", Age= 35, Description=""},
           new patientmodel(){Name="Moktar", Age= 50, Description=""},
            new patientmodel(){Name="Liban", Age= 55, Description=""},
    };

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM