我在用对象初始化程序初始化DataTable
指定Columns
和PrimaryKey
时遇到困难:
private DataTable _products = new DataTable
{
Columns = { { "Product", typeof(string) }, { "Lot", typeof(string) }, { "Qty", typeof(int) } },
PrimaryKey = Columns[0] //Columns doens't exist in the current context
};
有办法使它起作用吗?
不,如果要在对象中使用已初始化的对象,则不能使用对象初始化器语法。但这也没有多大意义。
而是使用构造函数,因为那是合适的位置:
private DataTable _products;
public void ClassName()
{
_products = new DataTable
{
Columns = { { "Product", typeof(string) }, { "Lot", typeof(string) }, { "Qty", typeof(int) } }
};
_products.PrimaryKey = new[] { _products.Columns[0] };
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句