List类有3个构造函数。
long id= 10;
List<long> testList = new List<long>(id); /*creating to List of long */
上面的语句给出了C#中的错误,并智能地说要将其转换为int。同时,当我像下面这样做时,它正在按预期工作。
long id= 10;
List<long> testList = new List<long>(); /*creating to List of long */
testList.Add(id);
背后的原因是什么?
列表初始化(可能是您想要做的(在C#中是这样完成的:
long id = 10;
List<long> testList = new List<long>() { id };
在大括号内,您可以放置多个用逗号分隔的元素,列表最初应包含这些元素。
public List()
public List(IEnumerable<T> collection)
public List(int capacity)
您正试图使用占用容量的构造函数(应该是int
,而不是long
(来初始化列表。
List.Add()
方法将数据添加到列表中。所以,创建列表对象v/s并将元素添加到列表的语句会导致错误。