문제

이것은 아마도 최고의 표시와 함께하는 예입니다.나는 열거 속성:

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 값을 문자열(반영하는 이름이)나는 이미 인스턴스가 있습니다.

지지 않는 더 나은 방법이 있을까?

도움이 되었습니까?

해결책

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

더 빠른 방법을 것을 정적으로 방출 IL 코드를 사용하여 동적 방법 및 ILGenerator.하지만 나는 이것을 사용하 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;
}

다른 팁

나는 일반적으로 반영하는 것은 매우 빠른 만큼 당신이 하지 않는 동적으로 호출 방법이 있습니다.
기 때문에 당신은 그냥 읽어의 특성을 열거,당신의 접근 방식 작동 없이도 잘 어떠한 실제 성능했다.

고 기억하는 일반적으로 유지하려고 간단한 일을 이해합니다.을 통해 엔지니어링이 그냥을 얻기 위해 몇 가지 ms 지 않을 수도 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top