2013-01-31 109 views
3

我有一個與構造函數的語法相關的問題,並在構造函數中拋出異常。如何在調用其他構造函數之前拋出ArgumentNullException

如何在調用CreateAnotherOne()之前爲參數b拋出ArgumentNullException,並在第二個構造函數中引發異常而不在檢查之後重複代碼?我可以將代碼提取到單獨的私有方法中,但我需要從兩個構造方法體中調用它...是否有其他選項可以實現此目的?

public class MyClass 
{ 
    public MyClass(IWhatEver a, ISomeThingElse b) 
     : this(a, b != null ? b.CreateAnotherOne() : null) 
    { 
     // or should I call :this(a, b.CreateAnotherOne()) instead? this could cause a NullReferenceException => how to verify that b is not null? 
     // don't want to call CallMeFromConstructor() instead of call to other constructor 

     // would not do the following (why should I check a/c twice?) and the check is too late here (because already called a method on b, b.CreateAnotherOne()) 
     if (a == null) 
     { 
      throw new ArgumentNullException("a"); 
     } 

     if (b == null) 
     { 
      throw new ArgumentNullException("b"); 
     } 
    } 

    public MyClass(IWhatEver c, IAnotherOne d) 
    { 
     if (c == null) 
     { 
      throw new ArgumentNullException("c"); 
     } 
     if (d == null) 
     { 
      throw new ArgumentNullException("d"); 
     } 

     // the cool code comes here, I could put it into 
     // the CallMeFromConstructor method but is there another way? 
    } 
    ... 

    private void CallMeFromConstructors() 
    { 
     // the cool code could be here, too (but is there another way?) 
    } 

如果我把與第二個構造函數:這個(!?A,B = NULL b.CreateAnotherOne():空)我會得到d INT第二構造一個ArgumentNullException。這聽起來很奇怪,而且可能會引起誤解,因爲我稱其爲第一個(只能在堆棧跟蹤中看到這一點)。

的問題是,我不能寫

:this(a, b == null ? b.CreateAnotherOne() : throw new ArgumentNullException("b")); 

,如果我把支票到構造體它被檢查下旬在這種情況下。

任何語法糖的想法來解決這個問題?

+0

//或者我應該叫:這個(A,B),而不是?這就是我會做的 – bas

+0

目前還不清楚你想要什麼。你能描述你想要的*行爲,而不是描述構造函數嗎? – Ran

+0

* NVM *評論刪除 – EtherDragon

回答

3

的私有方法將做到這一點,但你可以再拍私有的構造以及:

private MyClass(IWhatEver a) 
    { 
     if (a == null) 
     { 
      throw new ArgumentNullException("a"); 
     } 

     // the cool code comes here, I could put it into 
     // the CallMeFromConstructor method but is there another way? 
    } 

    public MyClass(IWhatEver a, ISomeThingElse b) : this(a) 
    { 
     if (b == null) 
     { 
      throw new ArgumentNullException("b"); 
     } 
    } 

    public MyClass(IWhatEver a, IAnotherOne b) : this(a) 
    { 
     if (b == null) 
     { 
      throw new ArgumentNullException("b"); 
     } 
    } 
+0

不錯的想法,這使得beeing的代碼被調用兩次,thx – Beachwalker

相關問題