[英]Add Item to List T Generic method
i'm not sure even it's possible but here the problem i'm trying to add item to List<T>
as follow 我不确定是否有可能,但是在这里我试图将项目添加到List<T>
的问题如下
public static SelectList ToSelectList<T>(List<T> addlist) where T : new ()
{
addlist.Insert(0, new T { Id = -1, Name = "SELECT" });
var list = new SelectList(addlist, "Id", "Name");
return list;
}
new T { Id = -1, Name = "SELECT" }
throwing error is it possible to add item to List<T>
? new T { Id = -1, Name = "SELECT" }
抛出错误是否可以将项目添加到List<T>
?
The problem is that, via the generic constraints, you have declared T
as any object with a default constructor. 问题在于,通过通用约束,您已将T
声明为具有默认构造函数的任何对象。
The compiler performs type checking at compile time, and T does not neccessarily have the properties Id
or Name
. 编译器在编译时执行类型检查,并且T不必具有属性Id
或Name
。
A solution is to 一个解决方案是
Id
and Name
, 创建一个具有Id
和Name
的接口, A compiling example: 一个编译示例:
public interface IEntity
{
int Id {get; set; }
string Name {get; set; }
}
class Widget : IEntity
{
public int Id {get; set; }
public string Name {get; set; }
public string SomeOtherProperty { get; set; }
}
public static SelectList ToSelectList<T>(List<T> addlist) where T : IEntity, new ()
{
addlist.Insert(0, new T { Id = -1, Name = "SELECT" });
var list = new SelectList(addlist, "Id", "Name");
return list;
}
// In your code
List<Widget> widgetList = new List<Widget>();
ToSelectList(widgetList);
The problem with your code is that you do not know what T
is and what properties it has. 代码的问题在于您不知道T
是什么以及它具有什么属性。 new
is not enough as your generic constraint. new
不足以作为您的一般约束。 All it specifies it: 所有它指定它:
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor 新约束指定通用类声明中的任何类型参数都必须具有公共的无参数构造函数
If you want to go and just instantiate an object of type T
then see: Create instance of generic type? 如果您想实例化T
类型的对象,请参见: 创建泛型类型的实例? . 。
But what might be better is just to create an interface with those properties, specify that your function gets a list of that type and then just instantiate an object of that type: 但是最好的办法是使用这些属性创建一个接口,指定您的函数获取该类型的列表,然后实例化该类型的对象:
public static SelectList ToSelectList(List<YourInterface> addlist)
{
addlist.Insert(0, new YourDerived { Id = -1, Name = "SELECT" });
var list = new SelectList(addlist, "Id", "Name");
return list;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.