C# 對象和集合初始化器

    爲了提供更合理的構造函數,我們不得不進行多次構造函數的重載,使得用戶的調用更加簡單。但是這樣的排列組合隨着參數的增加成幾何級增長,的確很不方便。現在有了Object and Collection Initializer(對象和集合初始化器)就方便多了。

     舉個例子:

 

private class Cat
{
    // Auto-implemented properties.
    public int Age { get; set; }
    public string Name { get; set; }
}
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
List<Cat> cats = new List<Cat>
{
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 },
    new Cat(){ Name = "Sasha", Age=14 }
};
    好了,常識性的普及就到這裏。現在讓我講講一些特殊的。
  • 如何初始化僅含有get的collection?

public class MyClass { public MyClass() { MyCollection = new List<string>(); } public List<string> MyCollection { get; private set; } }

正確的方式是:

MyClass test = new MyClass() { MyCollection = { "AAA", "BBB", "CCC" } };

 

  • 如何初始化Dictionary collection?

    public class MyClass

    {

        public Dictionary<int, string> MyDictionary { get; set; }

    }

正確的方法是:

            MyClass test = new MyClass()

            {

                MyDictionary = new Dictionary<int, string>()

                {

                    {1, "AAA"},

                    {2, "BBB"},

                    {3, "CCC"}

                }

            };

  • 什麼時候使用Nested的Initializer?

    一開始覺得寫Nested的Initializer,代碼不太好讀。現在發現的樹形結構裏使用Nested的Initializer能夠把樹的結構給表現得比較清楚。所以推薦大家也試試看。舉個WF 4.0的工作流樹吧。

            Sequence sequence = new Sequence()

            {

                DisplayName = "My Sequence",

                Activities =

                {

                    new WriteLine()

                    {

                        Text="Start"

                    },

                    new Flowchart()

                    {

                         DisplayName = "My Flowchart",

                         Nodes =

                         {

                             new FlowStep()

                             {

                                 Action = new If()

                                 {

                                     Else = new While(),

                                     Then = new Delay()

                                 }

                             }

                         }

                    },

                    new WriteLine()

                    {

                         Text="End"

                    }

                }

            };

     看,工作流就出來了,連帶着工作流的層級關係也表明了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章