gpt4 book ai didi

c# - 强制开发人员使用特定的构造函数

转载 作者:行者123 更新时间:2023-11-30 18:50:22 24 4
gpt4 key购买 nike

我有以下类(class)

  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;
}
}

我想确保开发人员仅在 chkSelect 不为 null 时才使用第一个构造函数。

我想做一个:

throw new ApplicationException("Dev is using the incorrect constructor");

最佳答案

您可以这样使用私有(private)构造函数:

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;
}

有很多变体,但作为一般规则,不太具体的构造函数会调用更具体的构造函数。例如,以下内容也适用于您的情况:

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;
}

关于c# - 强制开发人员使用特定的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/899725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com