简体   繁体   中英

Get Property Name of attached attribute

am sorry about the title i just had no idea how to call this. here is what i am trying to achieve.

[MyCustomAttribute]
string FormFirstName;

public MyCustomAttribute: Attribute
public MyCustomAttribute(something?){
  string propertyName = "FormFirstName";
}

Am trying to get a value inside my attribute that represents the name of the property that the attribute is attached to without having to give it to the attribute, no MyCustomAttribute("FormFirstName") the goal is to use reflection (i think) to get the name of the property and its type etc... it has to be doable on type string too.

THX :D

What you want simply cannot be done. An attribute does not know the member / type / etc upon which it was declared. You need to do it the other way around. When you're checking for the attribute's existence (because that isn't done automatically - you need to query for attributes via the reflection APIs), you can tell the attribute what it was on. For example:

var fieldInfo = ...
var attribs = (MyCustomAttribute[])Attribute.GetCustomAttributes(
    fieldInfo, typeof(MyCustomAttribute));
foreach(var attrib in attribs) {
    attrib.DoSomething(fieldInfo);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM