c# - 创建通用列表动态签名和分配对象
问题描述
我有一个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;
}
}
推荐阅读
- scala - Scala - 模式匹配 - 构造函数无法实例化为预期类型
- java - ArrayIndexOutOfBounds-数组对
- javascript - 使用自定义 javascript/css 更改了光标,但光标出现在大约 100px 右和低于实际指针的位置
- javascript - chrome 扩展即使在弹出窗口关闭时也能运行
- html - 如何将文本放在 HTML 电子邮件代码中的图像上?
- python - Python在列表中查找时间不连续
- r - rstudio 的 Ubuntu 内存问题
- ubuntu - Debian/Ubuntu:grub-customizer 无法启动
- python - 在 Python 中动态定义/更新 ctypes 结构
- php - 如何使用 Laravel JSON API?