C#:枚举反模式 [英] C#: Enum anti-patterns
问题描述
已经有一般违反清洁code-原则通话枚举的,所以我要找的人最喜欢的枚举反模式和替代解决方案的这些。
There has been talk of Enums in general violating Clean Code-principles, so I'm looking for people's favorite Enum anti-patterns and alternative solutions for these.
例如我见过code是这样的:
For example I've seen code like this:
switch(enumValue) {
case myEnum.Value1:
// ...
break;
case myEnum.Value2:
// ...
break;
}
这是一步好于开关语句与魔术的字符串,但是这可能是本来可以更好地解决了工厂,容器或其它图案。
It's one step better than switch-statements with magic strings, but this probably could have been solved better with a factory, a container or other pattern.
甚至老派code是这样的:
Or even old-school code like this:
if(enumValue == myEnum.Value1) {
// ...
} else if (enumValue == myEnum.Value2) {
// ...
}
什么其他的反模式,更好的实现有你经历了枚举
推荐答案
我觉得枚举是非常有用的。我已经写了增加了更多的价值,以将其用于枚举了一些扩展
I think Enums are quite useful. I've written a few extensions for Enum that have added even more value to its use
首先,有描述扩展方法
public static class EnumExtensions
{
public static string Description(this Enum value)
{
var entries = value.ToString().Split(ENUM_SEPERATOR_CHARACTER);
var description = new string[entries.Length];
for (var i = 0; i < entries.Length; i++)
{
var fieldInfo = value.GetType().GetField(entries[i].Trim());
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
description[i] = (attributes.Length > 0) ? attributes[0].Description : entries[i].Trim();
}
return String.Join(", ", description);
}
private const char ENUM_SEPERATOR_CHARACTER = ',';
}
这将让我定义的连接枚举是这样的:
This will allow me to define en enum like this:
public enum MeasurementUnitType
{
[Description("px")]
Pixels = 0,
[Description("em")]
Em = 1,
[Description("%")]
Percent = 2,
[Description("pt")]
Points = 3
}
和通过执行此操作获取标签: VAR myLabel = rectangle.widthunit.Description()
(无需任何一个开关
语句)。
And get the label by doing this: var myLabel = rectangle.widthunit.Description()
(eliminating any need for a switch
statement).
这将BTW返回PX如果 rectangle.widthunit = MeasurementUnitType.Pixels
,否则将会返回PX,EM如果 rectangle.widthunit = MeasurementUnitType.Pixels | MeasurementUnitType.Em
。
This will btw return "px" if rectangle.widthunit = MeasurementUnitType.Pixels
or it will return "px,em" if rectangle.widthunit = MeasurementUnitType.Pixels | MeasurementUnitType.Em
.
然后,有一
public static IEnumerable<int> GetIntBasedEnumMembers(Type @enum)
{
foreach (FieldInfo fi in @enum.GetFields(BindingFlags.Public | BindingFlags.Static))
yield return (int)fi.GetRawConstantValue();
}
这将让我穿越为int基于价值观的任何枚举,并返回整型值本身。
Which will let me traverse any enum with int based values and return the int values themselves.
我觉得这些是在一个媒体链接有用的概念非常有用。
I find these to be very useful in an allready useful concept.
这篇关于C#:枚举反模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!