I have a custom attribute:
public class MenuItemAttribute : Attribute { }
and a class with a few methods:
public class HelloWorld { [MenuItemAttribute] public void Shout() { } [MenuItemAttribute] public void Cry() { } public void RunLikeHell() { } }
How can I get only the methods that are decorated with the custom attribute?
So far, I have this:
string assemblyName = fileInfo.FullName; byte[] assemblyBytes = File.ReadAllBytes(assemblyName); Assembly assembly = Assembly.Load(assemblyBytes); foreach (Type type in assembly.GetTypes()) { System.Attribute[] attributes = System.Attribute.GetCustomAttributes(type); foreach (Attribute attribute in attributes) { if (attribute is MenuItemAttribute) { //Get me the method info //MethodInfo[] methods = attribute.GetType().GetMethods(); } } }
What I need now is to get the method name, the return type, as well as the parameters it accepts.
Retrieving a custom attribute is a simple process. 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.
The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
It is our ability to make meaning and to grow from our experiences that defines us as human and reflection is at the heart of all meaning making.
Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.
Your code is completely wrong.
You are looping through every type that has the attribute, which will not find any types.
You need to loop through every method on every type and check whether it has your attribute.
For example:
var methods = assembly.GetTypes() .SelectMany(t => t.GetMethods()) .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0) .ToArray();
Dictionary<string, MethodInfo> methods = assembly .GetTypes() .SelectMany(x => x.GetMethods()) .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any()) .ToDictionary(z => z.Name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With