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

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
}

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

有人有更好的方法吗?

有帮助吗?

解决方案

这可能是最简单的方法。

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

其他提示

我通常发现只要不动态调用方法,反射就相当快。
由于您只是读取枚举的属性,因此您的方法应该可以正常工作,而不会造成任何实际的性能影响。

请记住,您通常应该尽量使事情简单易懂。仅仅为了获得几毫秒的时间而过度设计可能不值得。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top