我想知道是否有办法初始化List< T>其中T是一个对象,就像一个简单的集合被初始化?
Simple Collection Initializer:
List<int> digits = new List<int> { 0,1,2,3,4,5,6,7,8,9 };
List<ChildObject> childObjects = new List<ChildObject> { new ChildObject(){ Name = "Sylvester",Age=8 },new ChildObject(){ Name = "Whiskers",Age=2 },new ChildObject(){ Name = "Sasha",Age=14 } };
问题是,如何以及如果你能做这样的事情?
List<ChildObject> childObjects = new List<ChildObject> { { "Sylvester",8},{"Whiskers",2},{"Sasha",14} };
解决方法
如果不创建自己从List< ChildObject>派生的类,则不能这样做.根据李的回答.遗憾的是,扩展方法不考虑用于收集初始化器,否则这将起作用:
// This doesn't work,but it would if collection initializers checked // extension methods. using System; using System.Collections.Generic; public class ChildObject { public string Name { get; set; } public int Age { get; set; } } public static class Extensions { public static void Add(this List<ChildObject> children,string name,int age) { children.Add(new ChildObject { Name = name,Age = age }); } } class Test { static void Main(string[] args) { List<ChildObject> children = new List<ChildObject> { { "Sylvester",8 },{ "Whiskers",2 },{ "Sasha",14 } }; } }