作者:mobiledu2502908023 | 来源:互联网 | 2023-07-25 19:19
privatestaticvoidMain(string[]args){varmessageTypetypeof(SampleHandler1);vargenericTypetyp
private static void Main(string[] args)
{
var messageType = typeof (SampleHandler1);
var genericType = typeof (IConsume<>).MakeGenericType(messageType);
var genericArguments = genericType.GetGenericArguments();
var cOnsumeMethod= genericType.GetMethod("Consume");
var cOnstructorInfo= genericArguments[0].GetConstructor(Type.EmptyTypes);
var classObject = constructorInfo.Invoke(new object[] {});
var argsx = new object[] {new SampleMessage {Name = "sample message"}};
consumeMethod.Invoke(classObject, argsx);
}
public interface IConsume where T : class
{
void Consume(T message);
}
public class SampleHandler1 : IConsume
{
public SampleHandler1()
{
Debugger.Break();
}
public void Consume(SampleMessage message)
{
Debugger.Break();
Console.WriteLine("Message consume: " + message.Name);
}
}
public interface IBaseMessage
{
}
public class SampleMessage : IBaseMessage
{
public string Name { get; set; }
}
我试着看这里,但我找不到具体的解决方案.正如MSDN解释的那样
obj
Type: System.Object
The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.
classObject是构造函数的一个实例,对吧?为什么会引发异常:
解决方法:
这似乎不对.让我们来分析一下这里发生了什么:
var messageType = typeof (SampleHandler1);
//simple enough, Type -> SampleHandler1
var genericType = typeof (IConsume<>).MakeGenericType(messageType);
//so genericType is a Type -> IConsume
var genericArguments = genericType.GetGenericArguments();
//there's only one, but Type[] { Type -> SampleHandler1 }
var cOnsumeMethod= genericType.GetMethod("Consume");
//MethodInfo -> IConsume.Consume(SampleHandler1)
var cOnstructorInfo= genericArguments[0].GetConstructor(Type.EmptyTypes);
//ConstructorInfo -> SampleHandler1..ctor()
var classObject = constructorInfo.Invoke(new object[] {});
//new SampleHandler1()
var argsx = new object[] {new SampleMessage {Name = "sample message"}};
//object[] { SampleMessage }
consumeMethod.Invoke(classObject, argsx);
//((IConsume)classObject).Consume( SampleMessage ) -- oops?
所以classObject是一个SampleHandler1,但你试图调用IConsume .Consume(SampleHandler1),更糟糕的是给它一个SampleMessage作为参数.
我认为您打算创建一个SampleHandler1,并在其上调用IConsume .Consume(SampleMessage):
var messageType = typeof(SampleMessage);
var genericType = typeof(IConsume<>).MakeGenericType(messageType);
var cOnsumeMethod= genericType.GetMethod("Consume");
var handlerType = typeof(SampleHandler1);
var cOnstructorInfo= handlerType.GetConstructor(Type.EmptyTypes);
var classObject = constructorInfo.Invoke(new object[] {});
var argsx = new object[] {new SampleMessage {Name = "sample message"}};
consumeMethod.Invoke(classObject, argsx);