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

Blo*_*ula 5 c# lambda

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

mik*_*002 4

根据框架设计指南

\n

setter 抛出异常是可以接受的

\n
\n

\xe2\x9c\x93 如果属性设置器抛出异常,请保留先前的值。

\n

\xe2\x9c\x93 DO 允许以任何顺序设置属性,即使这会导致对象的临时无效状态。

\n
\n

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

\n
public string QCode\n       { ... set {...\n                if (QBankCode.Length ==10 && value.Length % 2 == 0)\n                    throw new exception();...\n
Run Code Online (Sandbox Code Playgroud)\n

您的代码示例满足这一点,但您应该确保您的属性具有合理的默认值

\n
\n

\xe2\x9c\x93 DO 为所有属性提供合理的默认值,...

\n
\n