简体   繁体   English

如何在C#中使用反射来自定义方法列表

[英]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 . 另一种选择是放弃制作插件的自定义方式,并使用一些现成的东西,例如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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM