C# 反射、MethodInfo、GetMethods,仅包括仅由我添加的方法

C# 反射、MethodInfo、GetMethods,仅包括仅由我添加的方法,c#,C#,我是C#的新手 我编写了一个应用程序,它使用反射迭代选定对象的所有方法并运行它 问题在于MethodInfo[]methodInfos=typeof(ClassWithManyMethods).GetMethods()还返回方法,如ToString,GetType,我只想包括专门为我的类声明的方法 请看一下我的代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; usin

我是C#的新手

我编写了一个应用程序,它使用反射迭代选定对象的所有方法并运行它

问题在于
MethodInfo[]methodInfos=typeof(ClassWithManyMethods).GetMethods()
还返回方法,如
ToString
GetType
,我只想包括专门为我的类声明的方法

请看一下我的代码:

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


namespace Reflection4
{
    class ClassWithManyMethods
    {
    public void a()
    {
        Console.Write('a');
    }

    public void b()
    {
        Console.Write('b');
    }

    public void c()
    {
        Console.Write('c');
    }
}

class Program
{
    static void Main(string[] args)
    {
        // get all public static methods of MyClass type
        MethodInfo[] methodInfos = typeof(ClassWithManyMethods).GetMethods();
        ClassWithManyMethods myObject = new ClassWithManyMethods();

        foreach (MethodInfo methodInfo in methodInfos)
        {
            Console.WriteLine(methodInfo.Name);
            methodInfo.Invoke(myObject, null); //problem here!
        }
    }
}
使用以下各项:

DeclaredOnly指定仅在 应考虑提供的类型的层次结构。继承的成员是 没有考虑

使用以下各项:

DeclaredOnly指定仅在 应考虑提供的类型的层次结构。继承的成员是 没有考虑

添加到BindingFlags标志

typeof(ClassWithManyMethods).GetMethods(BindingFlags.DeclaredOnly | ...)
添加到BindingFlags标志

typeof(ClassWithManyMethods).GetMethods(BindingFlags.DeclaredOnly | ...)

在您的情况下,您需要指定所需的所有绑定标志:

BindingFlags.DeclaredOnly
BindingFlags.Public
BindingFlags.Instance
因此:


在您的情况下,您需要指定所需的所有绑定标志:

BindingFlags.DeclaredOnly
BindingFlags.Public
BindingFlags.Instance
因此:


增强代码的注释的教科书示例
//获取MyClass类型的所有公共静态方法
增强代码的注释示例
//获取MyClass类型的所有公共静态方法