简体   繁体   中英

Create Generic List<T> Signature and Assign Object Dynamically

I've an Interface where I am trying to create a generic List<T> and assign objects dynamically to it. Suppose as the following:

 public class Person
 {
    public string id { get; set; }
    public string name { get; set; }
 }

 public interface IPerson
 {
    List<T> Get<T>() where T :  new();
 }

Finally I tried to do the following to pass the list of person object:

class aPerson : IPerson
{
  public List<Person> Get<Person>() //The constraints for type parameter 'Person' of method 'Program.aPerson.Get<Person>()' must match the constraints for type parameter 'T' of interface method 'Program.IPerson.Get<T>()'
  {
    List<Person> aLst = new List<Person>()
    {
        new Person { id = "1001", name = "John" }, //Cannot create an instance of the variable type 'Person' because it does not have the new() constraint  
        new Person { id = "1002", name = "Jack" }
    };

    return aLst;
  }
}

I know, I am doing wrong here and expecting if someone could point out what could be the possible solution - Thanks.

The way you are using Generic Interface is incorrect, you can not the exact T type when you are implementing a generic Interface. In fact generic interfaces is a way of extending classes based interface you defined.

public interface IPerson<T>
{
    List<T> Get();
}

class aPerson : IPerson<Person>
{
    public List<Person> Get() 
    {
        var aLst = new List<Person>()
        {
            new Person { id = "1001", name = "John" },
            new Person { id = "1002", name = "Jack" }
        };
        return aLst;
    }
}

The error is because you don't have a parameter less constructor for the Person class, Having said that I would suggest a different approach for solving the issue.

public interface IPeople<T> where T: class
{
    List<T> Get();
}

public class People<Person>
{
    List<Person> Get()
    {
         var aLst = new List<Person>()
         {
                new Person { id = "1001", name = "John" }, 
                new Person { id = "1002", name = "Jack" }
         };

         return aLst;
    }
}

}

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