【问题标题】:How to get custom a list of methods with reflection in C#如何在 C# 中使用反射获取自定义方法列表
【发布时间】:2015-09-02 01:00:35
【问题描述】:

我一直在使用反射来创建用户将在动态生成的菜单中使用的方法列表(我很团结)。我正在使用:

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

但并非类的所有公共方法都应出现在此菜单中,所以我想知道,是否有一些标志可以用来仅标记我需要的方法?

然后使用这个“自定义标志”通过反射来获取这些方法。谢谢:)。

【问题讨论】:

  • 用自定义属性标记你需要的方法

标签: c# reflection unity-container bindingflags


【解决方案1】:

使用自定义属性:

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

并允许用户标记方法:

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

然后,在方法查找中,检查该属性的元数据:

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

如果您需要为用户提供定义菜单路径的功能,则使用自定义参数扩展您的属性,如下所示:

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

    public string MenuPath { get; }
}

另一种选择是放弃制作插件的自定义方式,并使用开箱即用的东西,例如MEF

【讨论】:

  • 嘿,谢谢!很好的答案!但是我没有“Where Method”的定义,我错过了什么? System.Reflection.MethodInfo[]' 不包含 `Where' 的定义
  • 好吧,我想 API 从 Unity C# 版本和 .NET C# 发生了变化,我终于用这个 SO 答案解决了这个问题:How would I use reflection... 但是你的回答很有帮助,让我走上了正确的道路,谢谢@丹尼斯
  • 这是 System.Linq 命名空间的扩展方法。它与 Unity API 无关。
【解决方案2】:

您可以使用以下代码。它将返回公共和非公共方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2023-04-05
    • 2011-07-25
    相关资源
    最近更新 更多