gpt4 book ai didi

c# - 在 C# 中编写不可变结构的最短方法

转载 作者:太空狗 更新时间:2023-10-29 19:52:23 24 4
gpt4 key购买 nike

我经常遇到对小型不可变数据结构的需求。其他人可能会在这些情况下使用元组,但我真的不喜欢元组读起来不好,也不能表达那么多的意思。 intValue2 没有告诉我任何信息。

一个例子是为两个属性的组合创建一个查找表(字典),即 NameRating

据我所知,为这些情况创建不可变结构的最短方法是:

public struct Key
{
public string Name { get; private set; }
public int Rating { get; private set; }

public LolCat(string name, int rating) : this()
{
Name = name;
Rating = rating;
}
}

// useage
var key = new Key( "MonorailCat", 5 );

在我看来,这里仍然有很多“语法脂肪”,我想摆脱掉。当我直接公开字段时,我可以使它更具可读性。

public struct Key
{
public string Name;
public int Rating;
}

// useage
var key = new Key { Name = "MonorailCat", Rating = 5 };

我真的很喜欢它的语法,因为它几乎没有任何语法脂肪。最大的缺点当然是它不是一成不变的,并且存在所有危险。

在理想情况下,我只想为此设置一个特殊类型,定义最少,例如:

public immutable struct Key
{
string Name;
int Rating;
}

// useage (needs compiler magic)
var key = new Key( Name: "MonorailCat", Rating: 5 );

问题

是否有更接近底部示例的真实世界解决方案,以减少非常简单的不可变结构的语法脂肪量?

最佳答案

从 C# 6 开始,您可以编写相当紧凑的 struct初始值设定项:

public struct Key
{
public string Name { get; }
public int Rating { get; }

public Key(string name, int rating)
{
this.Name = name;
this.Rating = rating;
}
}

...至少显着更短。我强烈建议实现 IEquatable<Key> ,请注意。

请注意,当您处理结构时,您仍然可以编写:

Key key = new Key();
Console.WriteLine(key.Rating); // 0

...这可能不是问题,但通常至少需要考虑

在 C# 6 之前,为了将属性写为只读属性,我实际上会比您当前的代码更长:

public struct Key
{
private readonly string name;
private readonly int rating;

public string Name { get { return name; } }
public int Rating { get { return rating; } }

public Key(string name, int rating)
{
this.name = name;
this.rating = rating;
}
}

我觉得这使得它更清楚地“意味着不可变”——如果你有一个可写的属性,即使 setter 只是私有(private)的,这也不会传达正确的印象 IMO。 (尽管值得注意的是,结构中的不变性始终是一个的伪装,因为您可以在成员中分配给 this...)

关于c# - 在 C# 中编写不可变结构的最短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25787244/

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