首页 > 解决方案 > 创建通用列表动态签名和分配对象

问题描述

我有一个Interface我试图创建一个通用List<T>并动态分配对象的地方。假设如下:

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

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

最后,我尝试执行以下操作来传递人员对象列表:

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;
  }
}

我知道,我在这里做错了,并期待有人能指出可能的解决方案 - 谢谢。

标签: c#asp.net

解决方案


您使用通用接口的方式不正确,当您实现通用接口时,您不能使用确切的 T 类型。事实上,泛型接口是一种扩展您定义的基于类的接口的方法。

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;
    }
}

推荐阅读