Can't use an “inline” array in C#?

前端 未结 3 425
无人共我
无人共我 2020-12-30 18:26

Imagine you have this somewhere

public static T AnyOne(this T[] ra) where T:class
    {
    int k = ra.Length;
    int r = Random.Range(0,k);
    re         


        
3条回答
  •  北海茫月
    2020-12-30 19:02

    You have to create the array first, using new[].

    string letter = (new[] {"a","b","c"}).AnyOne();
    

    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();
    

    And you can specify the data type new string[] as on other answers has been mentioned.


    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.

    Another reason will be that the compiler will be confused, won't know what to create, for example, a string[]{ .. } or a List{ .. }.

    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
    

提交回复
热议问题