Emiliano
Emiliano

Reputation: 39

How to get custom a list of methods with reflection in C#

I have being using reflection to create a list of methods that the user would use in a dynamic generated menu (I'am in unity). I'am using:

MethodInfo[] methodInfos =  myObject.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

But not all public methods of the class should appear in this menu, so I was wondering, is there some flag which I could use to mark only the methods that I need?

And then use this "custom flag" to get those methods through reflection. Thanks :).

Upvotes: 1

Views: 1785

Answers (2)

Shailendra Tiwari
Shailendra Tiwari

Reputation: 19

You could used below code. It will returns both public as well non public methods.

MethodInfo[] methodInfos =  myObject.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Upvotes: 2

Dennis
Dennis

Reputation: 37780

Use custom attribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MenuItemAttribute : Attribute
{
}

and allow user to mark methods:

public class Foo
{
    [MenuItem]
    public void Bar() {}
}

Then, on methods lookup, inspect metadata for this attribute:

var methodInfos = myObject
    .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
    .Where(_ => _.IsDefined(typeof(MenuItemAttribute)));

If you need to provide an ability for user to define menu path, then extend your attribute with custom parameter, something like this:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MenuItemAttribute : Attribute
{
    public MenuItemAttribute(string menuPath)
    {
        MenuPath = menuPath;
    }

    public string MenuPath { get; }
}

Another option is to throw away custom way to make plugins, and use something out of the box, e.g., MEF.

Upvotes: 7

Related Questions