枚举(简称 枚举类型)是对整型类型的一种简易语言包装形式。 在存储一组封闭值中的值时,你可能希望限制其使用范围。 基于大小(小、中、大)的分类是一个很好的示例。 对控制流或更强健的抽象使用枚举可成为代码气味。 这种用法会导致代码变得脆弱,因为有许多控制流语句需要检查枚举的值。
相反,可以创建枚举类来启用面向对象的语言的所有丰富功能。
但是,这不是一个关键主题,在许多情况下,为简单起见,如果这是首选,仍然可以使用常规 枚举类型 。 枚举类的使用与业务相关的概念更相关。
实现枚举基类
eShopOnContainers 中的排序微服务提供了一个示例枚举基类实现,如以下示例所示:
public abstract class Enumeration : IComparable
{
public string Name { get; private set; }
public int Id { get; private set; }
protected Enumeration(int id, string name) => (Id, Name) = (id, name);
public override string ToString() => Name;
public static IEnumerable<T> GetAll<T>() where T : Enumeration =>
typeof(T).GetFields(BindingFlags.Public |
BindingFlags.Static |
BindingFlags.DeclaredOnly)
.Select(f => f.GetValue(null))
.Cast<T>();
public override bool Equals(object obj)
{
if (obj is not Enumeration otherValue)
{
return false;
}
var typeMatches = GetType().Equals(obj.GetType());
var valueMatches = Id.Equals(otherValue.Id);
return typeMatches && valueMatches;
}
public int CompareTo(object other) => Id.CompareTo(((Enumeration)other).Id);
// Other utility methods ...
}
可将此类用作任何实体或值对象中的类型,如以下 CardType
: Enumeration
类:
public class CardType
: Enumeration
{
public static CardType Amex = new(1, nameof(Amex));
public static CardType Visa = new(2, nameof(Visa));
public static CardType MasterCard = new(3, nameof(MasterCard));
public CardType(int id, string name)
: base(id, name)
{
}
}
其他资源
吉米·博加德 Enumeration classes (枚举类)
https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/史蒂夫·史密斯 Enum Alternatives in C# (C# 中枚举的替代方案)
https://ardalis.com/enum-alternatives-in-cEnumeration.cs。 Base Enumeration class in eShopOnContainers(eShopOnContainers 中的基础枚举类)
https://github.com/dotnet-architecture/eShopOnContainers/blob/dev/src/Services/Ordering/Ordering.Domain/SeedWork/Enumeration.csCardType.cs。 eShopOnContainers 中的枚举类示例。
https://github.com/dotnet-architecture/eShopOnContainers/blob/dev/src/Services/Ordering/Ordering.Domain/AggregatesModel/BuyerAggregate/CardType.csSmartEnum。 Ardalis - 帮助在 .NET 中生成强类型智能枚举的类。
https://www.nuget.org/packages/Ardalis.SmartEnum/