【优化】放松对enum填法的要求,允许填合法的整数枚举值了

【调整】默认强迫枚举值唯一,减少意外错误
main
walon 2021-10-29 15:44:28 +08:00
parent 6e994e7729
commit ae5f92721b
2 changed files with 24 additions and 2 deletions

View File

@ -296,7 +296,7 @@ namespace Luban.Job.Common.Defs
private static readonly List<string> _enumRequiredAttrs = new List<string> { "name" }; private static readonly List<string> _enumRequiredAttrs = new List<string> { "name" };
private static readonly List<string> _enumItemOptionalAttrs = new List<string> { "value", "alias", "comment", "tags" }; private static readonly List<string> _enumItemOptionalAttrs = new List<string> { "value", "alias", "comment", "tags", "unique" };
private static readonly List<string> _enumItemRequiredAttrs = new List<string> { "name" }; private static readonly List<string> _enumItemRequiredAttrs = new List<string> { "name" };
protected void AddEnum(string defineFile, XElement e) protected void AddEnum(string defineFile, XElement e)
@ -309,6 +309,7 @@ namespace Luban.Job.Common.Defs
Comment = XmlUtil.GetOptionalAttribute(e, "comment"), Comment = XmlUtil.GetOptionalAttribute(e, "comment"),
IsFlags = XmlUtil.GetOptionBoolAttribute(e, "flags"), IsFlags = XmlUtil.GetOptionBoolAttribute(e, "flags"),
Tags = XmlUtil.GetOptionalAttribute(e, "tags"), Tags = XmlUtil.GetOptionalAttribute(e, "tags"),
IsUniqueItemId = XmlUtil.GetOptionBoolAttribute(e, "unique", true),
}; };
foreach (XElement item in e.Elements()) foreach (XElement item in e.Elements())

View File

@ -47,6 +47,8 @@ namespace Luban.Job.Common.Defs
private readonly Dictionary<string, int> _nameOrAlias2Value = new(); private readonly Dictionary<string, int> _nameOrAlias2Value = new();
private readonly Dictionary<int, string> _vaule2Name = new();
public bool TryValueByNameOrAlias(string name, out int value) public bool TryValueByNameOrAlias(string name, out int value)
{ {
return _nameOrAlias2Value.TryGetValue(name, out value); return _nameOrAlias2Value.TryGetValue(name, out value);
@ -74,9 +76,17 @@ namespace Luban.Job.Common.Defs
{ {
return value; return value;
} }
else if (int.TryParse(name, out value))
{
if (!_vaule2Name.ContainsKey(value))
{
throw new Exception($"{value} 不是 enum:'{FullName}'的有效枚举值");
}
return value;
}
else else
{ {
throw new Exception($"'{name}' 不是有效 枚举:'{FullName}' 值"); throw new Exception($"'{name}' 不是enum:'{FullName}'的有效枚举值");
} }
} }
@ -169,6 +179,17 @@ namespace Luban.Job.Common.Defs
{ {
throw new Exception($"enum:'{fullName}' 枚举名:'{Name}' alias:'{item.Alias}' 重复"); throw new Exception($"enum:'{fullName}' 枚举名:'{Name}' alias:'{item.Alias}' 重复");
} }
if (_vaule2Name.TryGetValue(item.IntValue, out var itemName))
{
if (IsUniqueItemId)
{
throw new Exception($"enum:'{fullName}' 枚举值:{item.IntValue} 重复. 枚举名:'{itemName}' <=> '{item.Name}'");
}
}
else
{
_vaule2Name.Add(item.IntValue, item.Name);
}
} }
} }