简体   繁体   中英

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

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, eg, MEF .

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

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