Кто-нибудь знает быстрый способ добраться до пользовательских атрибутов по значению enum? - PullRequest
17 голосов
/ 20 августа 2008

Это, вероятно, лучше всего показать на примере. У меня есть перечисление с атрибутами:

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 в строку (которая отражает имя) кажется мне грязным, когда у меня уже есть его экземпляр.

У кого-нибудь есть лучший способ?

Ответы [ 2 ]

10 голосов
/ 20 августа 2008

Это, наверное, самый простой способ.

Более быстрым способом было бы статически излучать код IL с использованием динамического метода и ILGenerator. Хотя я использовал это только для GetPropertyInfo, но не могу понять, почему вы не можете также создавать CustomAttributeInfo.

Например, код для выдачи геттера из свойства

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 голосов
/ 20 августа 2008

Я обычно нахожу отражение довольно быстрым, если вы не вызываете методы динамически.
Поскольку вы просто читаете атрибуты перечисления, ваш подход должен работать без каких-либо проблем с производительностью.

И помните, что вы, как правило, должны стараться сделать вещи простыми для понимания. Из-за этого просто выиграть несколько мс может не стоить.

...