[英]why reflection GetMethod return null?
I need to create an instance of object dynamically and execute one method of this instance dynamically. 我需要动态创建对象的实例,并动态执行该实例的一种方法。 I am trying this code but GetMethod return null.
我正在尝试此代码,但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();
and this is my SomeClass code: 这是我的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];
}
}
how can i solve this problem? 我怎么解决这个问题?
Activator.CreateInstance
returns a ObjectHandle
which needs to be unwrapped first: Activator.CreateInstance
返回一个ObjectHandle
,该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();
I have putted parameter null, might be due that this issue is comming, I have check this in console code is working fine 我已将参数设置为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];
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.