我有一个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;
}
}
我知道,我在这里做错了,希望有人能指出可能的解决方案——谢谢。
使用泛型接口的方式不正确,在实现泛型接口时不能使用确切的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;
}
}