可以使List<T>
子類:
public class BaseTypeList : List<BaseType>
{
public void Add(string x, string y, string z)
{
Add(new DerivedType { x = x, y = y, z = z });
}
}
然後你可以用更簡潔的集合初始化語法:
new BaseTypeList
{
{ "x1", "y1", "z1" },
{ "x2", "y2", "z2" },
{ "x3", "y3", "z3" },
{ "x4", "y4", "z3" /* (sic) */ },
//...
}
這工作,因爲編譯器來執行對每個元素單獨重載解析集合初始化程序塊,查找具有匹配給定參數的參數類型的Add方法。
如果需要均勻的派生類型,就有點難看,但它是可能的:
public class BaseTypeList : List<BaseType>
{
public void Add(Type t, string x, string y, string z)
{
Add((BaseType)Activator.CreateInstance(t, x, y, z));
}
}
那麼你會初始化這樣的集合:
new BaseTypeList
{
{ typeof(DerivedType1), "x1", "y1", "z1" },
{ typeof(DerivedType1), "x2", "y2", "z2" },
{ typeof(DerivedType2), "x3", "y3", "z3" },
{ typeof(DerivedType2), "x4", "y4", "z3" /* (sic) */ },
//...
}
我確定我只是老掉牙,但簡單的循環似乎更直截了當。 – 2013-03-15 22:04:03
@EricJ .:這取決於上下文。擁有單一表達式可以讓靜態變量初始化等事情變得更簡單......而LINQ方法更像是描述我們想要列表中的內容,而不是表達我們需要做什麼來創建它。 – 2013-03-15 22:06:00
@lazyberezovsky:它使用C#4,是的。將編輯以清楚說明。 – 2013-03-15 22:13:08