(C#)如何使用Mono.Cecil判断是否为枚举类型?
(C#) How to determine whether it is an enum type using Mono.Cecil?
如何使用Mono.Cecil判断是否为枚举类型??
只用Type.IsEnum就很容易判断了。但是我在TypeDefinition中找不到任何类似的函数...
有什么办法可以判断吗?
TypeDefinition
上有一个 IsEnum
属性。
哦,在你问下一个问题之前,这里是你如何使用 Cecil 将枚举字符串解析回它的 int 值...
int ParseEnum(TypeReference enumRef, string value)
{
var enumDef = enumRef.Resolve();
if (!enumDef.IsEnum)
throw new InvalidOperationException();
int? result = null;
foreach (var v in value.Split(',')) {
foreach (var field in enumDef.Fields) {
if (field.Name == "value__")
continue;
if (field.Name == v.Trim())
result = (result ?? 0) | (int)field.Constant;
}
}
if (result.HasValue)
return result.Value;
throw new Exception(string.Format("Enum value not found for {0}", value));
}
如何使用Mono.Cecil判断是否为枚举类型??
只用Type.IsEnum就很容易判断了。但是我在TypeDefinition中找不到任何类似的函数...
有什么办法可以判断吗?
TypeDefinition
上有一个 IsEnum
属性。
哦,在你问下一个问题之前,这里是你如何使用 Cecil 将枚举字符串解析回它的 int 值...
int ParseEnum(TypeReference enumRef, string value)
{
var enumDef = enumRef.Resolve();
if (!enumDef.IsEnum)
throw new InvalidOperationException();
int? result = null;
foreach (var v in value.Split(',')) {
foreach (var field in enumDef.Fields) {
if (field.Name == "value__")
continue;
if (field.Name == v.Trim())
result = (result ?? 0) | (int)field.Constant;
}
}
if (result.HasValue)
return result.Value;
throw new Exception(string.Format("Enum value not found for {0}", value));
}