首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对字符串数组进行HardCode?

如何对字符串数组进行HardCode?
EN

Stack Overflow用户
提问于 2012-02-03 04:09:13
回答 3查看 14.5K关注 0票数 3

我基本上想输入一个string[],并且能够基于换行符执行foreach。我试过这样做,但我不相信这能行得通。

代码语言:javascript
复制
static string[] mystrings = {"here"+
"there"+
"mine"
}

我想要一次一次地找到它,然后再回来。这个是可能的吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-02-03 04:10:17

您只需在花括号列表前面添加new[]new string[]即可。使用逗号,而不是加号。如图所示

代码语言:javascript
复制
string[] mystrings = new[] { "here", "there", "mine" };

仅供参考,C#提供的new[]快捷方式是语法糖,它可以推断您特指的是new string[]。如果要创建混合类型的数组(如object数组),则必须显式使用new object[],否则C#编译器不会知道您所暗示的是哪种类型。这就是:

代码语言:javascript
复制
// 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" } };
票数 12
EN

Stack Overflow用户

发布于 2012-02-03 04:11:27

代码语言:javascript
复制
static string[] myStrings = new string[] { "one", "two", "three" };

foreach(string s in myStrings)
{
     Console.WriteLine(s);
}
票数 1
EN

Stack Overflow用户

发布于 2012-02-03 04:10:58

代码语言:javascript
复制
static string[] items = new[] { "here", "there", "mine" };

然后

代码语言:javascript
复制
foreach (string item in items)
{
   System.Diagnostics.Debug.WriteLine(item);
}

但请记住,数组可以初始化一次,然后您就不能添加更多的项,我建议使用泛型列表List<string>

代码语言:javascript
复制
IList<string> items = new List<string> { "one", "two", "three" };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9119215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档