gpt4 book ai didi

c# - "Enum as immutable rich-object": is this an anti-pattern?

转载 作者:可可西里 更新时间:2023-11-01 07:46:45 30 4
gpt4 key购买 nike

我经常看到并使用带有附加属性的枚举来做一些基本的事情,例如提供显示名称或描述:

public enum Movement {
[DisplayName("Turned Right")]
TurnedRight,
[DisplayName("Turned Left")]
[Description("Execute 90 degree turn to the left")]
TurnedLeft,
// ...
}

并且有一组扩展方法来支持属性:

public static string GetDisplayName(this Movement movement) { ... }
public static Movement GetNextTurn(this Movement movement, ...) { ... }

按照此模式,可以将额外的现有或自定义属性应用于字段以执行其他操作。几乎就好像枚举既可以作为简单的枚举值类型工作,也可以作为具有多个字段的更丰富的不可变值对象工作:

public class Movement
{
public int Value { get; set; } // i.e. the type backing the enum
public string DisplayName { get; set; }
public string Description { get; set; }
public Movement GetNextTurn(...) { ... }
// ...
}

通过这种方式,它可以在序列化过程中作为一个简单的字段“移动”,进行快速比较等,但行为可以“内部化”(ala OOP)。

也就是说,我承认这可能被认为是一种反模式。同时,我的一部分认为这足够有用,anti 可能过于严格。

最佳答案

我认为这在 C# 中是一个糟糕的模式,仅仅是因为语言对声明和访问属性的支持非常糟糕;它们并不意味着存储大量数据。声明具有非平凡值的属性是一件痛苦的事情,获取属性的值也是一件痛苦的事情。一旦你想要一些与你的枚举相关联的远程有趣的东西(比如计算枚举上的东西的方法,或者包含非原始数据类型的属性),你要么需要将它重构为一个类,要么将其他东西放入一些带外的地方。

用一些包含相同信息的静态实例创建一个不可变类并没有变得更难,而且在我看来,它更符合习惯。

关于c# - "Enum as immutable rich-object": is this an anti-pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7881730/

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