是否可以将元素直接转换为数组?

vbb*_*ett 2 c# casting

有没有办法将单个对象T转换为T[]

使用它的一个例子是在将单个传递给string需要a的函数时string[]

void ExistingMethod(string[] sa);
void main()
{
  string s;
  ExistingMethod(s); //<= problem is there a syntax that allows this type of cast?
}
Run Code Online (Sandbox Code Playgroud)

对这样的解决方案不感兴趣

string [] singleElementArray = new string[1];
singleElementArray[0] = s;
ExistingMethod(singleElementArray)
Run Code Online (Sandbox Code Playgroud)

我想看看C#是否允许这种类型的铸造.

我以为我看到了Java允许它的一种方式,只需([s])用[] 将它包装起来即可.C#有这种语法吗?

注意,不想创建1的数组并分配它...

It'*_*ie. 13

更改foo(string[] sa)foo(params string[] sa).

params让你放一个采用数组参数参数数组的数组,如下所示:foo(foo, bar, baz);而不是foo(new[]{foo, bar, baz});

或者你可以做一个.Arr<T>(this T obj)函数,它返回一个T[].像这样的东西:

public static T[] Arr<T>(this T obj)
{
return new[]{ obj };
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

foo(obj.Arr());
Run Code Online (Sandbox Code Playgroud)