您可以创建一个子类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) */ },
//...
}