gpt4 book ai didi

C#、不变性和公共(public)只读字段

转载 作者:IT王子 更新时间:2023-10-29 04:05:10 27 4
gpt4 key购买 nike

我在很多地方都读到公开字段不是一个好主意,因为如果您以后想要更改属性,您将不得不重新编译所有使用您的类的代码。

但是,在不可变类的情况下,我不明白为什么您需要更改属性 - 毕竟您不会向“集合”添加逻辑。

对此有什么想法,我是否遗漏了什么?

区别的例子,对于那些比文本更容易阅读代码的人:)

//Immutable Tuple using public readonly fields
public class Tuple<T1,T2>
{
public readonly T1 Item1;
public readonly T2 Item2;
public Tuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
}

//Immutable Tuple using public properties and private readonly fields
public class Tuple<T1,T2>
{
private readonly T1 _Item1;
private readonly T2 _Item2;
public Tuple(T1 item1, T2 item2)
{
_Item1 = item1;
_Item2 = item2;
}
public T1 Item1 { get { return _Item1; } }
public T2 Item2 { get { return _Item2; } }
}

当然,您可以使用自动属性(public T1 Item1 { get; private set; }),但这只会让您获得“同意的不变性”,而不是“保证的不变性”。 .

最佳答案

C# 6.0 现在支持自动属性初始化程序。

The auto-property initializer allows assignment of properties directly within their declaration. For read-only properties, it takes care of all the ceremony required to ensure the property is immutable.

您可以在构造函数中或使用自动初始化器初始化只读属性

public class Customer
{
public Customer3(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string FirstName { get; }
public string LastName { get; }
public string Company { get; } = "Microsoft";
}

var customer = new Customer("Bill", "Gates");

您可以阅读有关自动属性初始化器的更多信息 here

关于C#、不变性和公共(public)只读字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2249980/

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