asp.net mvc获取当前属性属性值

时间:2016-12-11 07:42:25

标签: c# asp.net-mvc attributes

是否可以访问其他属性中关联属性的显示名称?例如,假设我将一个类定义为

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

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

我想在MyAttribute中访问显示名称,而无需手动编写属性名称

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我真的不明白,为什么你需要另一个属性呢。示例代码可以是:

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

        return displayName.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());

更新如果您只是想要,MyAttribute始终将属性设置为与DisplayName相同,则可以执行以下操作:

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;
    }
}
相关问题