5

なぜValue.GetType().GetCustomAttribute戻るのか誰か説明してもらえますnullか?列挙型メンバーの属性を取得する方法について、10 個の異なるチュートリアルを見てきました。どのGetCustomAttribute*方法を使用しても、カスタム属性が返されません。

using System;
using System.ComponentModel;
using System.Reflection;

public enum Foo
{
    [Bar(Name = "Bar")]
    Baz,
}

[AttributeUsage(AttributeTargets.Field)]
public class BarAttribute : Attribute
{
    public string Name;
}

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        return Value.GetType().GetCustomAttribute<BarAttribute>(true).Name;
    }
}
4

5 に答える 5

17

取得しようとしている属性が型に適用されていないためです。フィールドに適用されています。

したがって、型オブジェクトで GetCustomAttributes を呼び出すのではなく、FieldInfo オブジェクトで呼び出す必要があります。つまり、次のようなことを行う必要があります。

typeof(Foo).GetField(value.ToString()).GetCustomAttributes...
于 2013-01-11T19:42:33.500 に答える
2

問題のphoogの説明は正しいです。列挙値の属性を取得する方法の例が必要な場合は、この回答を確認してください。

于 2013-01-11T19:48:37.963 に答える
1

あなたの属性はフィールドレベルですが、Value.GetType().GetCustomAttribute<BarAttribute>(true).Name列挙型Fooに適用された属性を返します

于 2013-01-11T19:48:18.510 に答える
0

FooExtension を次のように書き換える必要があると思います。

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        string rv = string.Empty;
        FieldInfo fieldInfo = Value.GetType().GetField(Value.ToString());
        if (fieldInfo != null)
        {
            object[] customAttributes = fieldInfo.GetCustomAttributes(typeof (BarAttribute), true);
            if(customAttributes.Length>0 && customAttributes[0]!=null)
            {
                BarAttribute barAttribute = customAttributes[0] as BarAttribute;
                if (barAttribute != null)
                {
                    rv = barAttribute.Name;
                }
            }
        }

        return rv;
    }
}
于 2013-01-11T19:58:57.813 に答える
0

私はそれを次のように書き直しました:

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        var Type = Value.GetType();
        var Name = Enum.GetName(Type, Value);
        if (Name == null)
            return null;

        var Field = Type.GetField(Name);
        if (Field == null)
            return null;

        var Attr = Field.GetCustomAttribute<BarAttribute>();
        if (Attr == null)
            return null;

        return Attr.Name;
    }
}
于 2013-01-11T20:01:15.633 に答える