将对象转换为对象的单个项目数组(C#)

时间:2013-09-19 03:42:47

标签: c# arrays

有些函数只接受数组作为参数,但是你想为它们分配一个对象。例如,要为DataTable分配主键列,请执行以下操作:

DataColumn[] time = new DataColumn[1];
time[0] = timeslots.Columns["time"];
timeslots.PrimaryKey = time;

这看起来很麻烦,所以基本上我只需要将DataColumn转换为DataColumn[1] 数组。有没有更简单的方法呢?

4 个答案:

答案 0 :(得分:16)

您可以使用数组初始值设定语法编写它:

timeslots.PrimaryKey = new[] { timeslots.Columns["time"] }

这使用类型推断来推断数组的类型,并创建一个类型为timeslots.Columns [“time”]返回的数组。

如果你更喜欢这个数组是一个不同的类型(例如超类型),你也可以明确地说明这个

timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] }

答案 1 :(得分:6)

您也可以使用数组初始化程序在一行中写入:

timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] };

检查出来:All possible C# array initialization syntaxes

答案 2 :(得分:2)

timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] };

答案 3 :(得分:0)

根据以上答案,我创建了此扩展方法,该方法非常有用,可以节省很多输入时间。

/// <summary>
/// Convert the provided object into an array 
/// with the object as its single item.
/// </summary>
/// <typeparam name="T">The type of the object that will 
/// be provided and contained in the returned array.</typeparam>
/// <param name="withSingleItem">The item which will be 
/// contained in the return array as its single item.</param>
/// <returns>An array with <paramref name="withSingleItem"/> 
/// as its single item.</returns>
public static T[] ToArray<T>(this T withSingleItem) => new[] { withSingleItem };