Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the value of an attribute of a method

I need to be able to read the value of my attribute from within my Method, how can I do that?

[MyAttribute("Hello World")] public void MyMethod() {     // Need to read the MyAttribute attribute and get its value } 
like image 539
Coppermill Avatar asked Mar 22 '10 14:03

Coppermill


People also ask

Which method is used to retrieve the values of the attributes?

First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you can use its properties to get the values.

How to get value of attribute in javascript?

getAttribute() The getAttribute() method of the Element interface returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Non-existing attributes for details.

How to read property attributes in c#?

Use typeof(Book). GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttributes() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.


2 Answers

You need to call the GetCustomAttributes function on a MethodBase object.
The simplest way to get the MethodBase object is to call MethodBase.GetCurrentMethod. (Note that you should add [MethodImpl(MethodImplOptions.NoInlining)])

For example:

MethodBase method = MethodBase.GetCurrentMethod(); MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true)[0] ; string value = attr.Value;    //Assumes that MyAttribute has a property called Value 

You can also get the MethodBase manually, like this: (This will be faster)

MethodBase method = typeof(MyClass).GetMethod("MyMethod"); 
like image 192
SLaks Avatar answered Oct 18 '22 17:10

SLaks


[MyAttribute("Hello World")] public int MyMethod() { var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault(); } 
like image 25
Nagg Avatar answered Oct 18 '22 15:10

Nagg