[C#.NET] 為建構子建立正確的初始化

  • 32388
  • 0
  • 2013-07-05

[C#.NET] 為建構子建立正確的初始化

.NET4.0選擇性參數 還沒有出來以前,我們可能會為建構子建立以下的初始化方式

假設我有以下結構及類別

 

public class Class1
{
    public Info Company { get; set; }
    public Class1(string Name, int? Years, string Address)
    {
        this.createInfo(Name, Years, Address);
    }
    public Class1(string Name, int? Years)
    {
        this.createInfo(Name, Years, null);
    }
    public Class1(string Name)
    {
        this.createInfo(Name, null, null);
    }

    void createInfo(string Name, int? Years, string Address)
    {
        Info info = new Info();
        info.Name = Name;
        info.Years = Years;
        info.Address = Address;
    }
}


public struct Info
{
    public string Name { get; set; }
    public int? Years { get; set; }
    public string Address { get; set; }
}

這是很常見的建構子多載寫法,是為了初始化某個變數而定,上面的例子就是要初始化 Class1.Company 屬性,會依建構子傳入的參數多寡以及條件而建立不同的執行個體。

我們可以將上面的例子這樣改寫成這樣

public class Class2
{
    public Info Company { get; set; }
    public Class2(string Name, int? Years, string Address)
    {
        Info info = new Info();
        info.Name = Name;
        info.Years = Years;
    }
    public Class2(string Name, int? Years)
        : this(Name, Years, null)
    {
    }
    public Class2(string Name)
        : this(Name, null, null)
    {
    }
}

這兩種的寫法會得到相同的結果,前者的寫法在產生IL時每個建構子都重複了呼叫createInfo方法,而後者的寫法之會呼叫一次。

來看一下呼叫流程,當我在用戶端初始化執行個體時

Class2 c2 = new ClassLibrary1.Class2("余小章", null);

 

程式碼會先執行public Class2(string Name, int? Years, string Address){..}區塊,才會再執行public Class2(string Name, int? Years){..}區塊

image

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo