[英]Throw exception in constructor or validate parameters beforehand when creating an object?
我期待一個錯誤的參數,對象實例化經常發生。
應該IA)首先檢查參數然后創建對象(如果有效)。 B)創建由try / catch塊包圍的對象,並使構造函數在無效時拋出異常。
是否有理由選擇A或B而不是另一個?
另一個選擇是使用無參數構造函數和返回true
或false
的初始化方法。
這條路:
所以你的課程看起來像這樣:
class Foo
{
private Bar m_bar;
public Foo()
{
// do nothing here
}
public bool Initialize(Bar bar)
{
if (bar == null) // validation logic here
return false;
m_bar = bar;
return true;
}
}
class Check
{
private Some getsome;
public Some GetSome
{
get
{
return getsome;
}
set
{
if(value != null) //or any other logic you want
getsome = value; //if another logic like value < 10
else //you can throw - throw new ArgumentException - for example
throw new ArgumentNullException("value");
}
}
public Check()
{
}
}
如果你想在構造函數中傳遞它
public Check(Some s)
{
GetSome = s;
}
在contructor GetPage中的remenber是公共財產,所以你不要錯過檢查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.