lundi 9 novembre 2020

Get a custom attribute from a property with strong typing

I have a class Foo with a property Bar that has a custom attribute I'd like to retrieve.

public class Foo {
  [ThisAttribute("The string I want to get")]
  public string Bar { get; set; }
}

I could get the attribute value like so

var name = typeof(Foo).GetProperty("Bar").GetCustomAttribute(typeof(ThisAttribute)).PropertyName;

However, if the property were renamed, this would break. Is there a way to retrieve the attribute without hardcoding the string name of the property, and, rather, reference the specific property directly?





Aucun commentaire:

Enregistrer un commentaire