C# 为什么反射GetMethod返回null?

C# 为什么反射GetMethod返回null?,c#,reflection,C#,Reflection,我需要动态地创建一个object实例,并动态地执行该实例的一个方法。我正在尝试此代码,但GetMethod返回null var className = "SomeClass"; Type[] paramTypes = { typeof(Telegram.Bot.Types.User), typeof(string[]) }; var cmd = Activator.CreateInstance(null, "mynamespace." + className); var method = cmd

我需要动态地创建一个object实例,并动态地执行该实例的一个方法。我正在尝试此代码,但GetMethod返回null

var className = "SomeClass";
Type[] paramTypes = { typeof(Telegram.Bot.Types.User), typeof(string[]) };
var cmd = Activator.CreateInstance(null, "mynamespace." + className);
var method = cmd.GetType().GetMethod("Execute", BindingFlags.Public|BindingFlags.Instance, null, paramTypes, null);
res = method.Invoke(cmd, new object[] { e.Message.From, args }).ToString();
这是我的SomeClass代码:

public class RegisterTelegramCommand : ITelegramCommand
{
    public string Message
    {
        get
        {
            return "some message"; 
        }
    }

    public string Execute(Telegram.Bot.Types.User telegramUser, string[] param)
    {
        return param[0]+" " +param[2];           
    }
}
如何解决此问题?

返回需要首先展开的:

var className = "RegisterTelegramCommand";

Type[] paramTypes = { typeof(object), typeof(string[]) };
var cmd = Activator.CreateInstance("ConsoleApplication4", "ConsoleApplication4." + className);
Object p = cmd.Unwrap();
var method = p.GetType().GetMethod("Execute", BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null);
var res = method.Invoke(p, new object[] { null, args }).ToString();

我已经将参数设置为null,可能是因为这个问题即将出现,我已经在控制台代码中检查过这个是否正常工作

using System;
using System.Reflection;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            var className = "RegisterTelegramCommand";
            Type[] paramTypes = { typeof(object), typeof(string[]) };
            var cmd = Activator.CreateInstance("ConsoleApplication4", "ConsoleApplication4." + className);
            Object p = cmd.Unwrap();
            var method = p.GetType().GetMethod("Execute", BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null);
            var res = method.Invoke(p, new object[] { null, args }).ToString();
            Console.Read();
        }
    }

    public class RegisterTelegramCommand
    {
        public string Message
        {
            get { return "a"; }
        }

        public string Execute(object paramObject, string[] param)
        {
            return param[0] + " " + param[2];
        }
    }
}

另外粘贴
SomeClass的代码
?执行方法是私有的还是静态的?不,不是。这是一个公共方法。请注销
cmd.GetType()
并查看它是否是您的类型…按照@Gulam answer并将其展开,那么它应该可以工作。这是一个怎样的答案?它解决了我在空指针异常中的问题,但我现在得到了这个异常:System.Reflection.TargetException我在某个测试项目中测试了你的代码它工作得很好,但我在主项目中仍然有异常\n如果可能的话,你可以分享你的项目代码的一部分,以便在测试中确定确切的问题吗samechange命名空间和参数值正确如果您认为需要此代码,请更新其他答案,而不是发布新答案。您可以将此代码作为第一个代码的“第二个选项”提供。很抱歉,我刚刚开始分享我的知识,相信我也会在这方面有所改进。