Initializing list inline

前端 未结 4 388
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 00:26

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

public overrides List getSpaceballs
{
    get { return new List() { \"abc\         


        
4条回答
  •  囚心锁ツ
    2020-12-10 00:55

    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 { "foo", "bar" };
    

    However this statement is translated by the compiler to this:

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

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

提交回复
热议问题