不能使用"内联"数组中的C#? [英] Can't use an "inline" array in c#?
问题描述
想象一下,你有这样的地方
Imagine you have this somewhere
public static T AnyOne<T>(this T[] ra) where T:class
{
int k = ra.Length;
int r = Random.Range(0,k);
return ra[r];
}
甚至只是这个
or even just this
public static string OneOf(this string[] strings)
{
return "a";
}
然后,当然你也可以做到这一点...
Then, of course you can do this...
string[] st = {"a","b","c"};
string letter = st.AnyOne();
...这是伟大的。但。这样看来,你不能做到这一点:
... which is great. BUT. It would appear you can NOT do this:
string letter = {"a","b","c"}.AnyOne();
或事实上这也许
string letter = ( {"a","b","c"} ).AnyOne();
或其他任何东西我试过了。
or anything else I tried.
事实上(1)为什么人们不这样做呢? (2)我是失去了一些东西,你会怎么做,如果有一种方法?
In fact (1) why can one not do that? and (2) am I missing something, how would you do that if there is a way?
推荐答案
您必须创建数组首先,使用新[]
。
You have to create the array first, using new[]
.
string letter = (new[] {"a","b","c"}).AnyOne();
由于@hvd提到你可以做到这一点没有圆括号(..)
,我加了圆括号,因为我觉得它更具可读性。
As @hvd mentioned you can do this without parantheses (..)
, I added the parantheses because I think it's more readable.
string letter = new[] {"a","b","c"}.AnyOne();
和您可以指定数据类型新的String []
作为其他的答案已经被提及。
And you can specify the data type new string[]
as on other answers has been mentioned.
您不能只是做 { A,b,C}
,因为你可以把它作为一种填充数组,而不是创建它。
You can't just do {"a","b","c"}
, because you can think of it as a way to populate the array, not to create it.
另一个原因将是编译器会迷茫,不知道要创造什么,例如的String [] {..}
或列表<字符串方式> {...}
Another reason will be that the compiler will be confused, won't know what to create, for example, a string[]{ .. }
or a List<string>{ .. }
.
只需使用新[]
编译器可以通过的数据类型的(),知道
{...}
,你想要什么(字符串
)。关键部分是 []
,这意味着你需要一个数组。
Using just new[]
compiler can know by data type (".."
), between {..}
, what you want (string
). The essential part is []
, that means you want an array.
您甚至无法创建一个空阵列新[]
。
You can't even create an empty array with new[]
.
string[] array = new []{ }; // Error: No best type found for implicity-typed array
这篇关于不能使用"内联"数组中的C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!