有些函数只接受数组作为参数,但是你想为它们分配一个对象.例如,为DataTable
我指定一个主键列:
DataColumn[] time = new DataColumn[1];
time[0] = timeslots.Columns["time"];
timeslots.PrimaryKey = time;
Run Code Online (Sandbox Code Playgroud)
这看起来很麻烦,所以基本上我只需要将a转换DataColumn
为DataColumn[1]
数组.有没有更简单的方法呢?
Mar*_*oth 18
您可以使用数组初始化程序语法编写它:
timeslots.PrimaryKey = new[] { timeslots.Columns["time"] }
Run Code Online (Sandbox Code Playgroud)
这使用类型推断来推断数组的类型,并创建一个类型为timeslots.Columns ["time"]返回的数组.
如果您希望数组是一个不同的类型(例如超类型),您也可以将其显式化
timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] }
Run Code Online (Sandbox Code Playgroud)
您还可以使用数组初始化程序在一行中编写:
timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] };
Run Code Online (Sandbox Code Playgroud)
检查一下:所有可能的C#数组初始化语法