我基本上想输入一个string[],并且能够基于换行符执行foreach。我试过这样做,但我不相信这能行得通。
static string[] mystrings = {"here"+
"there"+
"mine"
}我想要一次一次地找到它,然后再回来。这个是可能的吗?
发布于 2012-02-03 04:10:17
您只需在花括号列表前面添加new[]或new string[]即可。使用逗号,而不是加号。如图所示
string[] mystrings = new[] { "here", "there", "mine" };仅供参考,C#提供的new[]快捷方式是语法糖,它可以推断您特指的是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" } };发布于 2012-02-03 04:11:27
static string[] myStrings = new string[] { "one", "two", "three" };
foreach(string s in myStrings)
{
Console.WriteLine(s);
}发布于 2012-02-03 04:10:58
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" };https://stackoverflow.com/questions/9119215
复制相似问题