2013-07-24 32 views
0

我试图创建显示属性CountryText反射在显示自定义属性MVC

[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的值的反射?

+0

您需要将'Sender'对象也加入到您的构造函数中,不幸的是,这对于一个属性是不可能的,因为您需要使用常量值 – LukeHennerley

回答

-1

既然是不可能的情况下传递给通过构造一个attribure,(即,属性包含在在编译时的元数据,并且然后通过反射使用时,可以看到Pass instance of Class as parameter to Attribute constructor

有一个工作角落找寻到通过实例,那就是做它在构造这样的:

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; 
     } 
     } 
    } 
    } 

,并在显示名称你做:

public override string DisplayName 
{ 
    get 
    { 
    var property = Instance.GetType().GetProperty(DisplayNameValue); 
    return property.GetValue(Instance, null) as string; 
    } 

} 

我不推荐这样的方法:(

+0

我不使用系统的资源文件,我有我自己的资源系统,所以我需要反射来获得值的关键名称和使用我自己的系统后得到的价值 – user1428798

+0

无论你将要使用的不是问题在这里,资源的价值关键是在DisplayNameValue中,你可以使用它希望你更喜欢的,我不知道你的上下文和我发布的是一个例子,你可以改变它并把它放在你的上下文中,我重复如果你需要resourceKey值,那么它是在DisplayNameValue – Swift

+0

我需要在我的例子属性CountryText的值 – user1428798