2010-04-13 198 views
1

我有一個C#的構造函數問題。C#構造函數問題

我有這個類:

public partial class Signature : Form, ISignature 
{ 
    private readonly SignatureMediator mediator; 

    public Signature(SignatureMediator mediator) 
    { 
     this.mediator = mediator; 
     InitializeComponent(); 
    } 

    .... more stuff 
} 

我要構建這個類是這樣的:

public SignatureMediator(int someValue, int otherValue, int thirdValue) 
     : this(new Signature(this), someValue, otherValue, thirdValue) 
    // This is not allowed --^ 
    { 
     // I don't see anyway to get this in to the ":this" part. 
     //Signature signature = new Signature(this); 

    }    


    public SignatureMediator(ISignature form, int someValue, int otherValue, int thirdValue) 
    { 
     SigForm = form; 
     SomeValue= someValue; 
     OtherValue= otherValue; 
     ThirdValue= thirdValue; 
    } 

: this(new SignatureThis(this)不允許(在構造函數中使用的this是不允許的)。

無論如何設置它而不重複int值的賦值?

+0

發佈片段不是獲得最佳答案的最佳方法。你對想象力太過分了。你想實現一個泛型類型,但沒有一個簡短的但完整的列表,你現有的類和接口的努力可能會被浪費。 – 2010-04-13 23:32:04

回答

4

如何讓第二個構造從this構建一個Signature如果ISignature參數null,否則使用提供ISignature?然後,您可以從第一個構造函數傳遞null以獲得所需的行爲。

public SignatureMediator(int someValue, int otherValue, int thirdValue) 
    : this(null, someValue, otherValue, thirdValue) 
{ 
}    

public SignatureMediator(ISignature form, int someValue, int otherValue, int thirdValue) 
{ 
    if (form == null) 
    { 
     SigForm = new Signature(this); 
    } 
    else 
    { 
     SigForm = form; 
    } 

    SomeValue = someValue; 
    OtherValue = otherValue; 
    ThirdValue = thirdValue; 
} 
0

由於未構造對象,因此不能將「this」作爲參數調用。相反,你將不得不鏈的建設:

public SignatureMediator(int w, int x, int y, int z) 
    : this(x,y,z) 
2

你絕對不能使用this構造函數調用鏈裏面,所以你必須調用它的構造函數體。最乾淨的方法是提取共同的初始化代碼放到一個單獨的方法,這樣的:

public SignatureMediator(int someValue, int otherValue, int thirdValue) 
{ 
    Initialise(someValue, otherValue, thirdValue) 
    SigForm = new Signature(this); 
}    


public SignatureMediator(ISignature form, int someValue, int otherValue, int thirdValue) 
{ 
    Initialise(someValue, otherValue, thirdValue) 
    SigForm = form; 
} 

private void Initialise(int someValue, int otherValue, int thirdValue) 
{ 
    SomeValue= someValue; 
    OtherValue= otherValue; 
    ThirdValue= thirdValue; 
} 

如果構建一個Signature對象是非常便宜的,你可以避開額外的方法,只是有第二個構造函數調用的第一個,然後使用傳入的值覆蓋它創建的SigForm值。

+1

調用初始化方法的構造函數的缺點是SomeValue,OtherValue和ThirdValue不能被聲明爲只讀,並且在構造函數以外的方法中被初始化 - 只有當你想要它們只讀時纔是問題。你的例子可能可以調整,使普通的init是一個私有的構造函數,這將避免一般的警告。 – 2010-04-13 23:59:07

+0

@Rob Parker - 很對,如果這是一個問題,你可以有一個虛構的參數的私人構造函數,只是爲了給它從另一個公開的簽名。 – EMP 2010-04-14 00:22:30

1

我從來沒有見過一個調解員負責構建它介於其間的對象。如果是這樣的話,它會將創造性的擔憂與調解混爲一談,即使沒有語法上的挑戰,這看起來也很難看。

爲什麼不按傳統GoF模式所建議的方式將調解器傳遞給Signature?您的客戶構造中介,然後他們將中介傳遞給中介介於其間的每個對象的構造函數。如果這太容易出錯,則可以使用Builder或工廠方法來構建對象。

+0

好點。我承認不確定我在用這種模式做什麼。 – Vaccano 2010-04-13 23:45:07