我有以下课程
public class UIControl
{
public string FName{ get; set; }
public HtmlInputCheckBox SelectCheckBox { get; set; }
public bool OverrideSelect { get; set; }
//Want to throw an ApplicationExceptioh if developer uses this constructor and passes
//chkSelect = null
public UIControl(string sFieldName, HtmlInputCheckBox chkSelect)
{
this.FName= sFieldName;
this.SelectCheckBox = chkSelect;
}
public UIControl(string sFieldName, HtmlInputCheckBox chkSelect, bool overrideSelect)
: this(sFieldName, chkSelect)
{
OverrideSelect = overrideSelect;
}
}
Run Code Online (Sandbox Code Playgroud)
我想确保开发人员仅在chkSelect不为null时才使用第一个构造函数.
我想做一个:
throw new ApplicationException("Dev is using the incorrect constructor");
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 13
您可以使用私有构造函数:
public UIControl(string sFieldName, HtmlInputCheckBox chkSelect)
: this(sFieldName, chkSelect, false, false)
{
}
public UIControl(string sFieldName, HtmlInputCheckBox chkSelect,
bool overrideSelect)
: this(sFieldName, chkSelect, overrideSelect, true)
{
}
private UIControl(string sFieldName, HtmlInputCheckBox chkSelect,
bool overrideSelect, bool allowOverride)
{
if ((!allowOverride) && (chkSelect == null))
throw new ArgumentException(...);
this.FName= sFieldName;
this.SelectCheckBox = chkSelect;
OverrideSelect = overrideSelect;
}
Run Code Online (Sandbox Code Playgroud)
有许多变体,但作为一般规则,具有较少特定构造函数调用更具体的变体.例如,以下内容也适用于您的情况:
public UIControl(string sFieldName, HtmlInputCheckBox chkSelect)
: this(sFieldName, chkSelect, false)
{
if (chkSelect == null) throw ...
}
public UIControl(string sFieldName, HtmlInputCheckBox chkSelect,
bool overrideSelect)
{
this.FName= sFieldName;
this.SelectCheckBox = chkSelect;
this.OverrideSelect = overrideSelect;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |