gpt4 book ai didi

c# - 什么是 C# 的 "moSTLy complete"(im) 可变性方法?

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

<分区>

尽管 CLR 中提供了一些支持,但由于不可变性并未完全融入 C# 到 F# 的程度,或者完全融入框架 (BCL),那么 C# 的(不)可变性的相当完整的解决方案是什么?

我的优先顺序是一个解决方案,由与以下内容兼容的一般模式/原则组成

  • 一个单一的开源库,几乎没有依赖性
  • 少量互补/兼容的开源库
  • 商业的东西

那个

  • 涵盖了 Lippert 的各种 immutability
  • 提供不错的性能(我知道这很模糊)
  • 支持序列化
  • 支持克隆/复制(深/浅/部分?)
  • 在 DDD、构建器模式、配置和线程等场景中感觉很自然
  • 提供不可变的集合

我还想包括您作为社区可能提出的模式,这些模式并不完全适合 expressing mutability intent through interfaces 等框架。 (不应该改变某些东西和可能想改变某些东西的客户端只能通过接口(interface)而不是支持类来改变(是的,我知道这是' t 真正的不变性,但足够了):

public interface IX
{
int Y{ get; }
ReadOnlyCollection<string> Z { get; }
IMutableX Clone();
}

public interface IMutableX: IX
{
new int Y{ get; set; }
new ICollection<string> Z{ get; } // or IList<string>
}

// generally no one should get ahold of an X directly
internal class X: IMutableX
{
public int Y{ get; set; }

ICollection<string> IMutableX.Z { get { return z; } }

public ReadOnlyCollection<string> Z
{
get { return new ReadOnlyCollection<string>(z); }
}

public IMutableX Clone()
{
var c = MemberwiseClone();
c.z = new List<string>(z);
return c;
}

private IList<string> z = new List<string>();
}

// ...

public void ContriveExample(IX x)
{
if (x.Y != 3 || x.Z.Count < 10) return;
var c= x.Clone();
c.Y++;
c.Z.Clear();
c.Z.Add("Bye, off to another thread");
// ...
}

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