2008-08-20 3 views
15

예를 들어 가장 잘 볼 수 있습니다. 내가 인스턴스에서 해당 속성에 도달 할누구나 enum 값에 대한 사용자 지정 특성을 빠르게 얻을 수있는 방법을 알고 있습니까?

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 
} 

하지만 열거를 변환 더러워 보인다 값을 이미 문자열이있는 문자열 (이름을 반영)로 변환합니다.

누구에게 더 좋은 방법이 있습니까?

+0

'Enum.GetName()'과 비교해 보셨습니까? –

답변

9

아마도 가장 쉬운 방법 일 것입니다.

동적 방법과 ILGenerator를 사용하여 IL 코드를 정적으로 방출하는 것이 더 빠릅니다. 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

내가 일반적으로 반사가 매우 빠른 것으로 찾아 속성에서 게터을 방출합니다.
열거 형의 특성을 읽었으므로 실제 성능이 저하되지 않으면 잘 작동합니다.

그리고 일반적으로 이해하기 쉽도록 노력해야한다는 것을 기억하십시오. 이것을 엔지니어링하는 것만으로 몇 분의 1 MS를 얻을 가치가 없을 수도 있습니다.

관련 문제