我正在使用 Dapper 来补充 C# 类。我最近从字符串常量集合转移到此处定义的“枚举类”:https ://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over -枚举类型
我的枚举如下所示:
public abstract class Enumeration : IComparable
{
public string Name { get; }
protected Enumeration(string name)
{
Name = name;
}
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var fields = typeof(T).GetFields(BindingFlags.Public |
BindingFlags.Static |
BindingFlags.DeclaredOnly);
return fields.Select(f => f.GetValue(null)).Cast<T>();
}
public static IEnumerable<T> ToSortedEnumerable<T>() where T : Enumeration
{
List<T> values = GetAll<T>().ToList();
values.Sort();
return values;
}
public int CompareTo(object other) =>
string.Compare(Name, ((Enumeration) other).Name, StringComparison.Ordinal);
public static implicit operator string(Enumeration enumeration)
{
return enumeration?.ToString();
}
public static bool operator ==(Enumeration e1, Enumeration e2)
{
return Equals(e1, e2);
}
public static bool operator !=(Enumeration e1, Enumeration e2)
{
return !Equals(e1, e2);
}
public static bool HasValue<T>(string valueToCheck) where T : Enumeration
{
return Enumeration.GetAll<T>().Any(x => x.Name.Equals(valueToCheck, StringComparison.OrdinalIgnoreCase));
}
public static bool TryGetEnumeration<T>(string valueToCheck, out T result) where T : Enumeration
{
result = Enumeration.GetAll<T>()
.FirstOrDefault(
x => x.Name.Equals(valueToCheck, StringComparison.OrdinalIgnoreCase));
return result != null;
}
回首忆惘然
守候你守候我
相关分类