带主键的 DataTable 对象初始值设定项

DataTable object initializer with Primary Key

我在使用对象初始化程序指定 ColumnsPrimaryKey 初始化 DataTable 时遇到困难:

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
    };

有没有办法让它起作用?

你应该这样写,

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 because, datatable is still initializing.
        };
        _products.PrimaryKey = new DataColumn[] {_products.Columns[0]}; //Columns exists here.

不,如果你想在其中使用一个也在其中初始化的对象,你不能使用 object initializer 语法。但这也没有多大意义。

而是使用构造函数,因为那是合适的地方:

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] };
}