簡體   English   中英

Reflection,MethodInfo,GetMethods,僅包括僅由我添加的方法

[英]Reflection, MethodInfo, GetMethods, include only methods only added by me

我是C#的新手。

我編寫了一個應用程序,它使用反射來遍歷所選對象的所有方法並運行它。

問題是MethodInfo[] methodInfos = typeof(ClassWithManyMethods).GetMethods(); 還返回ToStringGetType等方法,我想只包含專門為我的類聲明的方法。

請看看我的代碼:

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添加到BindingFlags標志。

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

在您的情況下,您需要指定所需的所有綁定標志:

BindingFlags.DeclaredOnly
BindingFlags.Public
BindingFlags.Instance

所以:

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

使用這個重載的GetMethods

var result = typeof(ClassWithManyMethods).GetMethods(BindingFlags.DeclaredOnly);

DeclaredOnly指定僅應考慮在提供的類型的層次結構級別聲明的成員。 不考慮繼承的成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM