gpt4 book ai didi

c# - 任何人都知道一种快速获取枚举值自定义属性的方法吗?

转载 作者:可可西里 更新时间:2023-11-01 03:01:03 24 4
gpt4 key购买 nike

这可能最好用一个例子来说明。我有一个带有属性的枚举:

public enum MyEnum {

[CustomInfo("This is a custom attrib")]
None = 0,

[CustomInfo("This is another attrib")]
ValueA,

[CustomInfo("This has an extra flag", AllowSomething = true)]
ValueB,
}

我想从实例中获取这些属性:

public CustomInfoAttribute GetInfo( MyEnum enumInput ) {

Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum )

//here is the problem, GetField takes a string
// the .ToString() on enums is very slow
FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() );

//get the attribute from the field
return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ).
FirstOrDefault() //Linq method to get first or null
as CustomInfoAttribute; //use as operator to convert
}

因为这是使用反射,所以我预计会有些慢,但是当我已经有了它的实例时,将枚举值转换为字符串(反射(reflect)名称)似乎很麻烦。

有没有人有更好的方法?

最佳答案

这可能是最简单的方法。

一种更快的方法是使用动态方法和 ILGenerator 静态发出 IL 代码。虽然我只将它用于 GetPropertyInfo,但不明白为什么您也不能发出 CustomAttributeInfo。

例如从属性发出 getter 的代码

public delegate object FastPropertyGetHandler(object target);    

private static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type)
{
if (type.IsValueType)
{
ilGenerator.Emit(OpCodes.Box, type);
}
}

public static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo)
{
// generates a dynamic method to generate a FastPropertyGetHandler delegate
DynamicMethod dynamicMethod =
new DynamicMethod(
string.Empty,
typeof (object),
new Type[] { typeof (object) },
propInfo.DeclaringType.Module);

ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
// loads the object into the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
// calls the getter
ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null);
// creates code for handling the return value
EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType);
// returns the value to the caller
ilGenerator.Emit(OpCodes.Ret);
// converts the DynamicMethod to a FastPropertyGetHandler delegate
// to get the property
FastPropertyGetHandler getter =
(FastPropertyGetHandler)
dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler));


return getter;
}

关于c# - 任何人都知道一种快速获取枚举值自定义属性的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com