我基本上想要输入一个字符串[]并且能够根据换行符进行foreach。我试过这样但我不相信这有效。
static string[] mystrings = {"here"+
"there"+
"mine"
}
我想要预先知道并一次取回一个。这可能吗?
答案 0 :(得分:9)
您只需在大括号列表前添加new[]
或new string[]
即可。并使用逗号,而不是加号。如在
string[] mystrings = new[] { "here", "there", "mine" };
仅供参考,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" } };
答案 1 :(得分:1)
static string[] myStrings = new string[] { "one", "two", "three" };
foreach(string s in myStrings)
{
Console.WriteLine(s);
}
答案 2 :(得分:0)
static string[] items = new[] { "here", "there", "mine" };
然后
foreach (string item in items)
{
System.Diagnostics.Debug.WriteLine(item);
}
但请记住,数组可以初始化一次,然后您无法添加更多项目,我建议使用通用列表List<string>
。
IList<string> items = new List<string> { "one", "two", "three" };