我正在查看一些旧代码,我很好奇在 setter 属性中包含逻辑是否合适,或者是否有更好的方法来编写它,为什么?谢谢你!
string qBankCode;
string qCode;
public string QBankCode
{
get => qBankCode;
set
{
if (value.Length == 0)
throw new ArgumentException("You need to enter the question bank code as it is mandatory.");
if (value.Length > 30)
throw new ArgumentException("Question bank code cannot exceed 30 characters.");
qBankCode = value;
}
}
public string QCode
{
get => qCode;
set
{
if (value.Length == 0)
throw new ArgumentException("You need to enter the question code as it is mandatory.");
if (value.Length > 30)
throw new ArgumentException("Question code cannot exceed 30 characters.");
qCode = value;
}
}
Run Code Online (Sandbox Code Playgroud)
根据框架设计指南:
\nsetter 抛出异常是可以接受的
\n\n\n\xe2\x9c\x93 如果属性设置器抛出异常,请保留先前的值。
\n\xe2\x9c\x93 DO 允许以任何顺序设置属性,即使这会导致对象的临时无效状态。
\n
只要它们不依赖于其他属性的状态,例如
\npublic string QCode\n { ... set {...\n if (QBankCode.Length ==10 && value.Length % 2 == 0)\n throw new exception();...\nRun Code Online (Sandbox Code Playgroud)\n您的代码示例满足这一点,但您应该确保您的属性具有合理的默认值
\n\n\n\xe2\x9c\x93 DO 为所有属性提供合理的默认值,...
\n
| 归档时间: |
|
| 查看次数: |
4335 次 |
| 最近记录: |