C# asp.net mvc获取当前属性值
是否可以访问其他属性中关联属性的显示名称?例如,假设我将一个类定义为C# asp.net mvc获取当前属性值,c#,asp.net-mvc,attributes,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;} }
public class Test
{
[DisplayName("First Name")]
[MyAttribute()]
public string SomeProperty {get;set;}
[DisplayName("Last Name")]
[MyAttribute()]
public string SomeOtherProperty {get;set;}
}
我想访问MyAttribute中的显示名称,而无需手动写入属性名称
有什么想法吗?我真的不明白,你为什么需要另一个属性呢。示例代码可以是:
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;
}
}
我真的不明白,为什么你需要另一个属性呢。示例代码可以是:
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;
}
}