Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建通用列表<;T>;动态签名和分配对象_C#_Asp.net - Fatal编程技术网

C# 创建通用列表<;T>;动态签名和分配对象

C# 创建通用列表<;T>;动态签名和分配对象,c#,asp.net,C#,Asp.net,我有一个界面,试图创建一个通用的列表,并为其动态分配对象。假设如下: public class Person { public string id { get; set; } public string name { get; set; } } public interface IPerson { List<T> Get<T>() where T : new(); } 公共类人物 { 公共字符串id{get;set;} 公共字符串

我有一个
界面
,试图创建一个通用的
列表
,并为其动态分配对象。假设如下:

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

 public interface IPerson
 {
    List<T> Get<T>() where T :  new();
 }
公共类人物
{
公共字符串id{get;set;}
公共字符串名称{get;set;}
}
公共接口IPerson
{
List Get()其中T:new();
}
最后,我尝试执行以下操作以传递person对象列表:

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;
  }
}
class-aPerson:IPerson
{
public List Get()//方法“Program.aPerson.Get()”的类型参数“Person”的约束必须与接口方法“Program.IPerson.Get()”的类型参数“T”的约束匹配
{
List aLst=新列表()
{
new Person{id=“1001”,name=“John”},//无法创建变量类型“Person”的实例,因为它没有new()约束
新人{id=“1002”,name=“Jack”}
};
返回aLst;
}
}

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

您使用泛型接口的方式是不正确的,您在实现泛型接口时无法确定确切的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;
    }
}

公共接口IPerson
{
List Get();
}
班级名称:IPerson
{
公共列表Get()
{
var aLst=新列表()
{
新人{id=“1001”,name=“John”},
新人{id=“1002”,name=“Jack”}
};
返回aLst;
}
}

公共接口IPerson{List Get(),其中T:new();}
这很奇怪,尤其是因为您有一个单独的(似乎不相关的)Person类。我在理解您的对象模型时遇到了很多麻烦。简单地说,当一个类型实现
IPerson
时,它意味着什么?现在,这意味着“调用者可以指定任何类,IPerson将返回它们的列表。”我不知道你为什么尝试在特定的情况下使用泛型,即Person类,请告诉我们你想做什么的更多细节。你是对的,你的修改并不明显。(很容易找到)。解释错误:public
List Get()
创建了一个名为“Person”的新泛型参数,其含义与List完全相同。它与类Person完全没有关系。因此,它最终的含义是新的T{id=“1001”…},这毫无意义。