Enumeration 类

一个强类型枚举(Smart Enum)基类。

⚠️ 重要:枚举项必须使用"单例写法",否则会埋下隐患。

推荐(整个进程内唯一实例):

public static readonly CardType Amex = new(1, nameof(Amex)); // 字段 public static CardType Visa { get; } = new(2, nameof(Visa)); // 只读属性

不推荐(每次访问都 new 一个新实例):

public static CardType MasterCard => new(3, nameof(MasterCard)); // ❌ 每次访问都 new

原因:Enumeration 内部会缓存每个枚举项,FromIdT(Int32) / FromNameT(String) 返回的是缓存中的那个实例,而属性写法每次 返回新实例。虽然 Equals / == 仍会判定相等,但以下场景会出问题:

  • 用枚举项做 Dictionary / HashSet 的 key 时,引用不一致
  • 用 ReferenceEquals 判断时结果不符预期
  • 附加了可变字段(未来扩展)时,实例状态无法共享

完整用法示例:

public class CardType : Enumeration { public static readonly CardType Amex = new(1, nameof(Amex)); public static readonly CardType Visa = new(2, nameof(Visa)); public static readonly CardType MasterCard = new(3, nameof(MasterCard)); public CardType(int id, string name) : base(id, name) { } }

Definition

命名空间: Suresking.Utility
程序集: Suresking.Utility (在 Suresking.Utility.dll 中) 版本:1.3.22+a27276bb8ffde055e69ff608e98aafba279e1e99
C#
public abstract class Enumeration : IComparable, 
	IComparable<Enumeration>, IEquatable<Enumeration>
Inheritance
Object    Enumeration
Implements
IComparable, IComparableEnumeration, IEquatableEnumeration

构造函数

Enumeration 构造函数

属性

Id 唯一标识(参与相等性、哈希与比较)
Name 显示名称

方法

AbsoluteDifference 比较两个枚举项的 Id 差的绝对值
CompareTo(Enumeration)Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
CompareTo(Object)Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
Equals(Enumeration)Indicates whether the current object is equal to another object of the same type.
Equals(Object)Determines whether the specified object is equal to the current object.
(重写 ObjectEquals(Object))
FromIdT 用 Id 反向构建枚举项(O(1) 查找)
FromNameT 用 Name 反向构建枚举项(O(1) 查找)
GetAllT 获取该枚举类的所有枚举项(字段 + 属性),结果已缓存。
GetAllFieldsT 获取该枚举类的所有·字段类型·枚举项

必须同时满足:字段、Public、Static、在本类声明而不是继承来的

GetAllPropertiesT 获取该枚举类的所有·属性类型·枚举项

必须同时满足:属性、Public、Static、在本类声明而不是继承来的

GetHashCodeServes as the default hash function.
(重写 ObjectGetHashCode)
ToStringReturns a string that represents the current object.
(重写 ObjectToString)
TryFromIdT 尝试用 Id 查找,找不到返回 false(不抛异常)
TryFromNameT 尝试用 Name 查找,找不到返回 false(不抛异常)

运算符

参见