gpt4 book ai didi

c# - 具有非空保护子句的自动实现的属性?

转载 作者:可可西里 更新时间:2023-11-01 03:10:38 25 4
gpt4 key购买 nike

我同意 Mark Seeman 的观点,即 Automatic Properties are somewhat evil因为他们打破了封装。然而,我确实喜欢它们带来的简洁语法、可读性和便利性。

我引用:

public string Name { get; set; }

The problem with the code snippet isn’t that it contains too much ceremony. The problem is that it breaks encapsulation. In fact

“[…] getters and setters do not achieve encapsulation or information hiding: they are a language-legitimized way to violate them.”

James O. Coplien & Gertrud Bjørnvig. Lean Architecture. Wiley. 2010. p. 134.

大多数时候,添加一个非 null 保护子句对于属性 setter 来说已经足够了,我想知道是否有比以下方法更好的方法。我所说的更好,是指以更简洁/更少重复的方式。

使用代码契约:

private string _username;
public virtual string Username
{
get { return _username; }
set
{
Contract.Requires(value != null);
_username = value;
}
}

使用 Vanilla .NET:

private string _username;
public virtual string Username
{
get { return _username; }
set
{
if (value == null) throw new ArgumentNullException("Username");
_username = value;
}
}

最佳答案

我只引用 Code Contracts手册,§ 2.3.1:

public int MyProperty { get; private set ; }

[ContractInvariantMethod]
private void ObjectInvariant ()
{
Contract. Invariant ( this.MyProperty >= 0 );
...
}

关于c# - 具有非空保护子句的自动实现的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6773189/

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