有人知道如何快速获取枚举值的自定义属性吗?

21

最好的方式是通过一个例子来展示。我有一个带有属性的枚举:

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
}

由于使用了反射,我预计会有一些减慢,但是当我已经拥有一个实例时,将枚举值转换为字符串(反映名称)似乎很混乱。

有没有更好的方法?


你尝试过使用Enum.GetName()进行比较吗? - Mark Cidade
2个回答

11

这可能是最简单的方法。

更快的方法是使用动态方法和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;
}

7

如果您不动态调用方法,我认为反射速度还是很快的。
由于您只是读取枚举的属性,因此您的方法应该可以正常工作,而不会对性能产生实质性影响。

请记住,通常应该尽量保持简单易懂。过度设计只为了获得几毫秒的优势可能并不值得。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接