Why can I initialize a List like an array in C#?

前端 未结 6 1015
清歌不尽
清歌不尽 2020-12-12 23:20

Today I was surprised to find that in C# I can do:

List a = new List { 1, 2, 3 };

Why can I do this? What constructor

6条回答
  •  被撕碎了的回忆
    2020-12-12 23:56

    The array like syntax is being turned in a series of Add() calls.

    To see this in a much more interesting example, consider the following code in which I do two interesting things that sound first illegal in C#, 1) setting a readonly property, 2) setting a list with a array like initializer.

    public class MyClass
    {   
        public MyClass()
        {   
            _list = new List();
        }
        private IList _list;
        public IList MyList 
        { 
            get
            { 
                return _list;
            }
        }
    }
    //In some other method
    var sample = new MyClass
    {
        MyList = {"a", "b"}
    };
    

    This code will work perfectly, although 1) MyList is readonly and 2) I set a list with array initializer.

    The reason why this works, is because in code that is part of an object intializer the compiler always turns any {} like syntax to a series of Add() calls which are perfectly legal even on a readonly field.

提交回复
热议问题