C# 显示自定义属性mvc中的反射
我正在尝试创建一个显示属性CountryText值的自定义属性C# 显示自定义属性mvc中的反射,c#,asp.net-mvc,data-annotations,system.reflection,C#,Asp.net Mvc,Data Annotations,System.reflection,我正在尝试创建一个显示属性CountryText值的自定义属性 [DisplayNameProperty("CountryText")] public string Country { get; set; } public string CountryText { get; set; } 这是属性的代码 namespace Registration.Front.Web.Validators { public class RegistrationDisp
[DisplayNameProperty("CountryText")]
public string Country { get; set; }
public string CountryText { get; set; }
这是属性的代码
namespace Registration.Front.Web.Validators
{
public class RegistrationDisplayNameAttribute:DisplayNameAttribute
{
private readonly PropertyInfo _proprtyInfo;
public RegistrationDisplayNameAttribute(string resourceKey):base(resourceKey)
{
}
public override string DisplayName
{
get
{
if(_proprtyInfo==null)
}
}
}
}
如何进行反射以获取属性代码中名为resourceKey的fild的值???因为不可能通过构造函数将实例传递给属性库,即属性在编译时包含在元数据中,然后通过反射使用,您可以看到 传递实例需要做一项工作,就是在构造函数中这样做:
public class Foo
{
[RegistrationDisplayNameAttribute("MyProp2")]
public string MyProp { get; set; }
public string MyProp2 { get; set; }
public Foo()
{
var atts = this.GetType().GetCustomAttributes();
foreach (var item in atts)
{
if (atts is RegistrationDisplayNameAttribute)
{
((RegistrationDisplayNameAttribute)atts).Instance = this;
}
}
}
}
在DisplayName中,您可以执行以下操作:
public override string DisplayName
{
get
{
var property = Instance.GetType().GetProperty(DisplayNameValue);
return property.GetValue(Instance, null) as string;
}
}
我不推荐这种方法:您也需要将Sender对象放入构造函数中,不幸的是,这不可能与属性一起使用,因为您需要使用常量值。我不使用资源文件系统,我有自己的资源系统,所以我需要反射来获取键名的值,在使用我自己的系统来获取键名之后,不管你要使用什么,这里都不是问题,资源键的值在DisplayNameValue中,你可以随意使用它,我不知道你的上下文,我发布的是一个示例,你可以更改它并将它放到你的上下文中,我重复一遍,如果您需要resourceKey值,那么它就在DisplayNameValues中。在我的示例中,我需要属性CountryText的值