2016-03-03 25 views
0

這是典型的課程。如何停止在C#中工作構造函數?

class Round 
{ 
    private int radius; 

    private bool Validate(int radius) 
    { 

      if (radius <= 0) 
      { 
      return false; 
      } 
      else 
     { 
      return true; 
     } 

    } 

    public int X { get; set;} 
    public int Y { get; set;} 

    public int Radius 
    { 
     get 
     { 
      return radius; 
     } 

     set 
     { 
      try 
      { 
       if(!Validate(value)) 
       { 
        throw new ArgumentException(); 
       } 
      radius = value; 
      } 
      catch (ArgumentException) 
      { 

       Console.WriteLine("ooops... something went wrong."); 
       return; 
      } 

     } 
    } 

    public Round (int X, int Y, int radius) 
    { 

     try 
     { 
      if (!Validate(radius)) 
      { 
       throw new ArgumentException(); 
      } 
     this.X = X; 
     this.Y = Y; 
     this.radius = radius; 
     } 
     catch (Exception) 
     { 

      Console.WriteLine("ooops... something went wrong."); 
     } 
    } 

    public double GetPerimeter() 
    { 
     return Math.PI * radius * 2; 
    } 

} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Round r = new Round(0,0,0); 
     Console.WriteLine(r.GetPerimeter()); 
    } 
} 

正如您所看到的,我將錯誤的值發送給將值發送給驗證器的構造函數。我不明白我該怎麼做才能讓構造函數停止創建對象???。

+2

如果意想不到的事情在構造時,你拋出一個' Exception'。如果您不想拋出異常,則可以使用靜態類方法來生成類的實例(「Factory」)。 –

+0

您不能停止構造函數,但可以拋出異常 –

+0

您可以對異常*和*做出反應,讓它通過重新拋出而傳播到外層。在'catch'塊中用'throw'替換'return'。 –

回答

5

停止構造函數的方法是拋出異常。

你正在那樣做,但你也正在捕捉異常。這樣,構造函數將繼續。不要抓住它。

0

,如果你不想扔在構造函數中的異常,你可以考慮這種方法

// constructor 
public Round (int X, int Y, int radius) 
{ 
    this.X = X; 
    this.Y = Y; 
    this.radius = radius; 
} 

// create instance 
public static Round CreateInstance(int X, int Y, int radius) 
{ 
    if (!Validate(radius)) 
    { 
     return null; 
    } 
    return new Round(X, Y, radius); 
} 

如何使用:

// invalid should be null 
Round invalid = Row.CreateInstance(1, 1, -1);