C# 初始化列表内联

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2020407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:44:47  来源:igfitidea点击:

Initializing list inline

c#

提问by John

I'm getting a weird error when doing this: (.net 2.0)

这样做时我遇到了一个奇怪的错误:(.net 2.0)

public overrides List<String> getSpaceballs
{
    get { return new List<String>() { "abc","def","egh" }; }
}

VS is asking for ;after (). Why?

VS是要求;()。为什么?

I sure can do this:

我肯定可以做到这一点:

public overrides string[] getSpaceballs
{
    get { return new string[] { "abc","def","egh" }; }
}

采纳答案by Noon Silk

The first option is not legal :)

第一个选项不合法:)

You can only do that type of initialiser on arrays.

您只能在数组上执行这种类型的初始化程序。

-- Edit: See Andrew Hare'spost (and others, below); it is only available in v3 and up.

- 编辑:请参阅Andrew Hare 的帖子(以及下面的其他帖子);它仅在 v3 及更高版本中可用。

-- Edit again:

-- 再次编辑:

Just to be clear, if your compiler is of 3 or greater, you can target 2.0, to get this to work (because it's compiled down to the code that Andrew shows, below). But if your compiler is 2, then you can't.

需要明确的是,如果您的编译器是 3 或更高版本,您可以将目标设为 2.0,以使其工作(因为它已编译为下面 Andrew 显示的代码)。但是如果你的编译器是 2,那么你就不能。

回答by Andrew Hare

C#'s collection initialization syntaxis only supported in versions 3 and up (since you mentioned .NET 2.0 I am going to assume you are also using C# 2). It can be a bit confusing since C# has always supported a similar syntax for array initialization but it is not really the same thing.

C# 的集合初始化语法仅在版本 3 及更高版本中受支持(因为您提到了 .NET 2.0,我将假设您也在使用 C# 2)。这可能有点令人困惑,因为 C# 一直支持类似的数组初始化语法,但实际上并不是一回事。

Collection initializers are a compiler trick that allows you to create and initialize a collection in one statement like this:

集合初始值设定项是一种编译器技巧,允许您在如下语句中创建和初始化集合:

var list = new List<String> { "foo", "bar" };

However this statement is translated by the compiler to this:

但是这个语句被编译器翻译成这样:

List<String> <>g__initLocal0 = new List<String>();
<>g__initLocal0.Add("foo");
<>g__initLocal0.Add("bar");
List<String> list = <>g__initLocal0;

As you can see, this feature is a bit of syntax sugar that simplifies a pattern into a single expression.

如您所见,此功能是一种语法糖,可将模式简化为单个表达式。

回答by C. Ross

As the other users point out, that is not supported in 2.0. However, you can mimic it by doing the following.

正如其他用户指出的那样,2.0 不支持。但是,您可以通过执行以下操作来模仿它。

public overrides List<String> getSpaceballs
{
   get { return new List<String> ( new String[] {"abc","def","egh"} ); }
}

Please note that this creates some computational overhead.

请注意,这会产生一些计算开销。