gpt4 book ai didi

c# - 可以将逻辑放在 C# 属性的 setter 中吗?

转载 作者:太空狗 更新时间:2023-10-30 00:47:41 26 4
gpt4 key购买 nike

我正在查看一些旧代码,我很好奇在 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;
}
}

最佳答案

根据Framework Design Guidelines :

setter抛出异常是可以接受的

✓ DO preserve the previous value if a property setter throws an exception.

✓ DO allow properties to be set in any order even if this results in a temporary invalid state of the object.

只要它们不依赖于其他属性的状态,例如

public string QCode
{ ... set {...
if (QBankCode.Length ==10 && value.Length % 2 == 0)
throw new exception();...

您的代码示例符合此要求,但您应该确保您的属性具有合理的默认值

✓ DO provide sensible default values for all properties, ...

关于c# - 可以将逻辑放在 C# 属性的 setter 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107772/

26 4 0