Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c# - Initializing list inline

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

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

VS is asking for ; after (). Why?

I sure can do this:

public overrides string[] getSpaceballs
{
    get { return new string[] { "abc","def","egh" }; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

C#'s collection initialization syntax is 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...