【问题标题】:Get only the current class members via Reflection通过反射仅获取当前类成员
【发布时间】:2014-05-08 12:12:13
【问题描述】:

假设这段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace TestFunctionality
{
  class Program
  {
    static void Main(string[] args)
    {
      // System.Reflection.Assembly.GetExecutingAssembly().Location
      Assembly assembly = Assembly.LoadFrom("c:\\testclass.dll");
      AppDomain.CurrentDomain.Load(assembly.GetName());
      var alltypes = assembly.GetTypes();
      foreach (var t in alltypes)
      {
        Console.WriteLine(t.Name);
        var methods = t.GetMethods(/*BindingFlags.DeclaredOnly*/);
        foreach (var method in methods)
        Console.WriteLine(
        "\t--> "
        +(method.IsPublic? "public ":"")
        + (method.IsPrivate ? "private" : "") 
        + (method.IsStatic ? "static " : "") 
        + method.ReturnType + " " + method.Name);
      }
      Console.ReadKey();
    }
  }
}

我正在尝试从基类中获取在此类中定义但不是的方法的定义。即,我不想得到类似的东西

System.String ToString() // A method in the base class object.

我怎样才能过滤掉它们?

我试图通过 BindingFlags.DeclaredOnly 但这会过滤所有内容。 这是在 testclass.dll 内:

namespace TestClass
{
public class Class1
    {
      public static int StaticMember(int a) { return a; }
      private void privateMember() { }
      private static void privateStaticMember() { }
      public void PublicMember() { }
      public void PublicMember2(int a) { }
      public int PublicMember(int a) { return a; }
    }
}

你有什么建议?

谢谢。

【问题讨论】:

    标签: c# .net-assembly system.reflection


    【解决方案1】:

    你想要这个:

    cl.GetMethods(BindingFlags.DeclaredOnly |
        BindingFlags.Instance |
        BindingFlags.Public);
    

    根据MSDN documentation,它声明DeclaredOnly

    指定只应考虑在提供的类型层次结构级别声明的成员。不考虑继承的成员。

    现在,也许你明确想要不是的方法public:

    cl.GetMethods(BindingFlags.DeclaredOnly |
        BindingFlags.Instance |
        BindingFlags.NonPublic);
    

    如果你想要both public 和非public 方法,请执行以下操作:

    cl.GetMethods(BindingFlags.DeclaredOnly |
        BindingFlags.Instance |
        BindingFlags.Public |
        BindingFlags.NonPublic);
    

    请注意,每个查询都包含InstancePublicNonPublic,这是因为文档说明如下:

    您必须指定 InstanceStatic 以及 PublicNonPublic没有成员返回

    【讨论】:

    • +1 注意:对于私有成员,这是默认行为。你只会得到声明的成员。
    • @SriramSakthivel,等等,NonPublic 不会也抢到protected 成员吗?这些将被继承。
    • 我不得不承认我考虑过保留我的 +1 以使用“选项非常无限”这句话。我敢肯定没有超过一百万个选项... ;-)
    • @MichaelPerrenoud 我认为protected 不会被收回。懒得测试了。我想这对所有非公开都是如此。
    • 当我使用 DeclaredOnly 时,我只得到类名。我更新了问题以显示更好的示例代码。
    【解决方案2】:

    我想你想要 DeclaredOnly 绑定标志

    【讨论】:

    • 它必须是标志的组合,否则你不会得到结果
    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 2013-02-02
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多