我有一个相当通用的“规则”类,我用它来驱动我正在编写的分析引擎的行为:
public class Rule
{
/// <summary>
/// The general rule type.
/// </summary>
public RuleType RuleType { get; set; }
/// <summary>
/// The human-readable description of the rule.
/// </summary>
public string RuleDescription { get; set; }
/// <summary>
/// The integer magnitude of the rule, if applicable.
/// </summary>
public int? RuleInt { get; set; }
/// <summary>
/// The boolean sign associated with the rule, if applicable.
/// </summary>
public bool? RuleBool { get; set; }
/// <summary>
/// The enum flag associated with the rule, if applicable. CAN be null.
/// </summary>
public System.Enum RuleFlagEnum { get; set; }
/// <summary>
/// A dumping ground for any other random crap I've failed to account for at this point in time.
/// </summary>
public object RuleObject { get; set; }
}
RuleType 是一个特定的枚举,如下所示:
public enum RuleType
{
Invalid,
ModifyDifficulty,
StrengthChange,
ColorChange,
SignChange
}
使用 Json.NET,序列化和反序列化都很好。
然而,RuleEnum 给我带来了问题。无论是使用默认的枚举序列化还是字符串枚举序列化,都没有提供枚举的具体类型。因此,在反序列化过程中,我留下了System.Enum
和一个字符串值,这完全没有帮助。
这是序列化的示例,以展示我在说什么:
{
"RuleType": "SignChange",
"RuleDescription": "Strength 1 Inversion Gate",
"RuleInt": 1,
"RuleFlagEnum": "Negative"
}
在本例中,RuleFlagEnum 指的是枚举:
public enum SignChange
{
Zero,
Positive,
Negative
}
我尝试过使用所有的TypeNameHandling
Json.NET 中的选项。他们只在对象上添加类型提示,这对 RuleFlagEnum 没有帮助,因为它在技术上是一个原语。
我真的非常想将枚举保留在 System.Enum 中,这样我们就可以加载任何任意枚举,以便以后通过规则类型进行解释,因此整个事情更具可扩展性。这可能吗?