这个不可变 属性 可以转换为自动 属性 吗?
Can this immutable property be converted to an auto property?
我一直在研究我正在开发的应用程序,它大量使用了不变性。我刚刚发现 getter-only 自动属性在 C# 6.0 中,所以我正在重构以使用它们。不过,我遇到了一个可能的问号,即我通过 public 属性将 private IList<T>
对象公开为 ReadOnlyCollection<T>
,以避免将它们恢复为原始状态的可能性List<T>
对象,例如
private IList<string> tags = new List<string>();
public IEnumerable<string> Tags => new ReadOnlyCollection<string>(this.tags);
有什么方法可以使用这种自定义类型的自动属性 getter?
很遗憾,没有。自动属性是没有具有自定义 getter 或 setter 的属性的快捷方式。
作为旁注:正如 Sinatr 在评论中正确提到的那样,您将在每次 属性 调用时创建一个 ReadOnlyCollection 的新实例。这对于 属性 来说是不典型的。考虑每次都返回相同的实例:
private IList<string> tags = new List<string>();
public IEnumerable<string> Tags { get; }
public MyClass()
{
Tags = new ReadOnlyCollection<string>(this.tags);
}
之所以有效,是因为 ReadOnlyCollection
反映了对基础集合所做的更改:
An instance of the ReadOnlyCollection<T>
generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.
注意:需要构造函数:C# 不允许字段初始值设定项引用其他实例字段,因为 the compiler might rearrange the initialization order。在VB.NET中,字段按照出现的顺序进行初始化,可以这样写:
Private tagList As New List(Of String)()
Public ReadOnly Property Tags As IEnumerable(Of String) = New ReadOnlyCollection(Of String)(tagList)
我一直在研究我正在开发的应用程序,它大量使用了不变性。我刚刚发现 getter-only 自动属性在 C# 6.0 中,所以我正在重构以使用它们。不过,我遇到了一个可能的问号,即我通过 public 属性将 private IList<T>
对象公开为 ReadOnlyCollection<T>
,以避免将它们恢复为原始状态的可能性List<T>
对象,例如
private IList<string> tags = new List<string>();
public IEnumerable<string> Tags => new ReadOnlyCollection<string>(this.tags);
有什么方法可以使用这种自定义类型的自动属性 getter?
很遗憾,没有。自动属性是没有具有自定义 getter 或 setter 的属性的快捷方式。
作为旁注:正如 Sinatr 在评论中正确提到的那样,您将在每次 属性 调用时创建一个 ReadOnlyCollection 的新实例。这对于 属性 来说是不典型的。考虑每次都返回相同的实例:
private IList<string> tags = new List<string>();
public IEnumerable<string> Tags { get; }
public MyClass()
{
Tags = new ReadOnlyCollection<string>(this.tags);
}
之所以有效,是因为 ReadOnlyCollection
反映了对基础集合所做的更改:
An instance of the
ReadOnlyCollection<T>
generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.
注意:需要构造函数:C# 不允许字段初始值设定项引用其他实例字段,因为 the compiler might rearrange the initialization order。在VB.NET中,字段按照出现的顺序进行初始化,可以这样写:
Private tagList As New List(Of String)()
Public ReadOnly Property Tags As IEnumerable(Of String) = New ReadOnlyCollection(Of String)(tagList)