如何HardCode一个字符串数组?

3 c# string

我基本上想要输入一个字符串[]并且能够根据换行符进行foreach.我试过这样但我不相信这有用.

static string[] mystrings = {"here"+
"there"+
"mine"
}
Run Code Online (Sandbox Code Playgroud)

我想要预先知道并一次取回一个.这可能吗?

Jos*_*nig 11

您只需添加new[]new string[]在卷括号列表前面.并使用逗号,而不是加号.如在

string[] mystrings = new[] { "here", "there", "mine" };
Run Code Online (Sandbox Code Playgroud)

仅供参考,new[]捷径是由C#提供的语法糖,这意味着你特别指的是new string[].如果要创建混合类型的数组(例如数组object),则必须显式使用new object[],否则C#编译器将不知道您所暗示的类型.那是:

// Doesn't work, even though assigning to variable of type object[]
object[] myArgs = new[] { '\u1234', 9, "word", new { Name = "Bob" } };

// Works
object[] myArgs = new object[] { '\u1234', 9, "word", new { Name = "Bob" } };

// Or, as Jeff pointed out, this also works -- it's still commas, though!
object[] myArgs = { '\u1234', 9, "word", new { Name = "Bob" } };

// ...althouth this does not, since there is not indication of type at all
var myArgs = { '\u1234', 9, "word", new { Name = "Bob" } };
Run Code Online (Sandbox Code Playgroud)

  • 如果要初始化变量,则不必严格地使用`new []`部分,但是包括它始终是一个好主意。 (2认同)