为什么反射GetMethod返回null?

时间:2017-05-02 09:16:43

标签: c# reflection

我需要动态创建一个对象实例并动态执行该实例的一个方法。我正在尝试使用此代码,但 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];           
    }
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

Activator.CreateInstance返回ObjectHandle,需要首先解包:

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();

答案 1 :(得分:1)

我已经推出了参数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];
        }
    }
}