我目前正在开发批准路由WCF服务,该服务允许用户创建"规则",以确定如何路由请求.通过将Request类的"ObjectToEvaluate"属性与"Rule"类的"ObjectToEvaluate"属性进行比较来确定路由."UnitOfMeasurement"枚举确定如何为每个类强制转换"ObjectToEvaluate"属性.
public enum UnitOfMeasurement { Currency = 1, Numeric = 2, Special = 3, Text = 4, } public class Request { public object ObjectToEvaluate { get; set; } } public class Rule { public object ObjectToEvaluate { get; set; } public virtual void ExecuteRule() { //logic to see if it passes the rule condition } }
使用"UnitOfMeasurement"枚举实现方法来转换"ObjectToEvaluate"属性的最佳方法是什么?
使用隐式类型运算符来检查枚举的值.这样,调用者可以透明地将对象分配给您想要表示它们的类型.例如:
public class CastableObject { private UnitOfMeasurement eUnit; // Assign this somehow public static implicit operator int(CastableObject obj) { if (obj.eUnit != UnitOfMeasurement.Numeric) { throw new InvalidCastException("Mismatched unit of measurement"); } // return the numeric value } // Create other cast operators for the other unit types }