1

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 :).

Emiliano
  • 39
  • 1
  • 7

2 Answers2

7

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.

Dennis
  • 37,026
  • 10
  • 82
  • 150
  • Hey, thanks ! Great answer ! However I don't have a definition for the "Where Method", what I'am missing ? System.Reflection.MethodInfo[]' does not contain a definition for `Where' – Emiliano Sep 01 '15 at 16:58
  • Well I suppose that the API changes from the Unity C# version and .NET C#, I finally solved this with this SO answer: [How would I use reflection...](http://stackoverflow.com/questions/2831809/how-would-i-use-reflection-to-call-all-the-methods-that-has-a-certain-custom-att) But your answer was very helpful and got me on the right track, thanks @Dennis – Emiliano Sep 01 '15 at 19:04
  • This is the extension method from System.Linq namespace. It's not related to Unity API. – Dennis Sep 01 '15 at 21:47
2

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);