18

これは、おそらく例で最もよく示されています。私は属性を持つ列挙型を持っています:

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
}

これはリフレクションを使用しているため、多少の遅延が予想されますが、列挙値のインスタンスが既にある場合に、列挙値を文字列 (名前を反映する) に変換するのは面倒です。

誰かがより良い方法を持っていますか?

4

2 に答える 2

11

これはおそらく最も簡単な方法です。

より迅速な方法は、動的メソッドと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;
}
于 2008-08-20T12:01:50.027 に答える
7

メソッドを動的に呼び出さない限り、通常、リフレクションは非常に高速であることがわかります。
列挙型の属性を読み取っているだけなので、実際のパフォーマンスに影響を与えることなく、アプローチは問題なく機能するはずです。

また、一般的に物事を理解しやすいようにシンプルに保つ必要があることを忘れないでください。数ミリ秒を取得するためだけにこれを設計しすぎると、価値がない場合があります。

于 2008-08-20T12:46:12.040 に答える