0

I'm trying to create a custom attribute that display the value of property CountryText

[DisplayNameProperty("CountryText")]
    public string Country { get; set; }

    public string CountryText { get; set; }

this the code of the attribute

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)

                }

            }
        }
    }

How can i do the reflexion to obtain the value of the fild named resourceKey in my code of attribute??

user1428798
  • 1,534
  • 3
  • 24
  • 50
  • You would need to get the `Sender` object into your constructor too, unfortunately this is impossible to do with an attribute as you need to use constant values – LukeHennerley Jul 24 '13 at 09:12

1 Answers1

-1

Since it is impossible to pass instances to an attribure via constructor, (i.e the attributes are included in metadata at compile time, and then used via reflexion, you can see Pass instance of Class as parameter to Attribute constructor)

There is a work arround to pass the instance, and that is to do it in the constructor like that:

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

and in the DisplayName you do:

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

}

I don't recommend such method :(

Community
  • 1
  • 1
Swift
  • 1,861
  • 14
  • 17
  • i dont use a system of resource file, i have my own system of ressource, so i need the reflexion to get the value o key name and after use my own system to get value – user1428798 Jul 24 '13 at 09:59
  • Whatever you are gonna use is not the issue here, the value of the resource key is in DisplayNameValue, you can use it howerver you wish, I don't know your context and what i posted is an example, you can change it and put it in your context, I repeat if you need the resourceKey value then it is in DisplayNameValue – Swift Jul 24 '13 at 10:04
  • i need the value of the property CountryText in my example – user1428798 Jul 24 '13 at 10:06