我经常看到并使用带有属性的枚举来完成一些基本任务,例如提供显示名称或描述:
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(...) { ... }
// ...
}
这样,它可以在序列化期间作为一个简单的字段“传递”,快速比较等,但行为可以被“内部化”(类似于面向对象编程)。
话虽如此,我认识到这可能被视为反模式。与此同时,我认为其中一部分很有用,以至于“反”可能太严格了。
dynamic
一样。 - Kit.hisHer()
方法和其他返回特定于性别的字符串的方法。 - Brandon Buck