2016-12-11 18 views
1

他の属性の関連プロパティの表示名にアクセスできますか?例えば、私は手動でプロパティ名asp.net mvc現在のプロパティ属性値を取得

任意のアイデアを記述することなく

public class Test 
{ 
    [DisplayName("First Name")] 
    [MyAttribute()] 
    public string SomeProperty {get;set;} 

    [DisplayName("Last Name")] 
    [MyAttribute()] 
    public string SomeOtherProperty {get;set;} 
} 

私はMyAttributeで表示名にアクセスするなど、クラスを定義したと言いますか?

答えて

0

私は本当に理解していません、なぜあなたはそれのために別の属性が必要ですか?サンプルコードは次のようになります。使用に

public class MyAttribute : Attribute 
{ 
    public static string GetAttribute(MemberInfo m) 
    { 
     var displayName =(DisplayNameAttribute)Attribute 
           .GetCustomAttribute(m, typeof(DisplayNameAttribute)); 

     return displayName.DisplayName; 
    } 
} 

:あなたはMyAttributeは、常にプロパティがDisplayNameと同じに設定したことを

//First Name 
var firstName= MyAttribute.GetAttribute(typeof(Test) 
        .GetMember(nameof(Test.SomeProperty)).First()); 
//Last Name 
var lastName = MyAttribute.GetAttribute(typeof(Test) 
        .GetMember(nameof(Test.SomeOtherProperty)).First()); 

UPDATEあなただけの場合、あなたはこのような何かを行うことができます:

public class MyAttribute : Attribute 
{ 
    public string Display { get; set; } 
    public MyAttribute([CallerMemberName] string propertyName = null) 
    { 
     Display = ((DisplayNameAttribute)GetCustomAttribute(typeof(Test).GetMember(propertyName).First(), typeof(DisplayNameAttribute))).DisplayName; 
    } 
} 
関連する問題