简体   繁体   English

如何创建动作 <T> 形成通过反射给出的对象方法?

[英]How to create an Action<T> form an object method given via Reflection?

I have a void SubscribeToPublish<TMessage>(Action<TMessage> action) method. 我有一个void SubscribeToPublish<TMessage>(Action<TMessage> action)方法。 And it expects an Action<T> . 并且它期望一个Action<T> I have an object created purely from Type in a way like this: 我有一个纯粹从Type创建的对象,如下所示:

var Node =  Activator.CreateInstance(type);
var methods = type.GetMethods(BindingFlags.Public).Where(methodInfo => methodInfo.GetParameters().Count() == 1).ToList();
methods.ForEach(methodInfo => {
    SubscribeToPublish(o => methodInfo.Invoke( pair.Value.Node, o )); // Here I see error cannot be inferred from usage.
});

Thus I wonder: how to create Action<T> on the go having objects created via Reflection? 因此,我想知道:如何在通过反射创建对象的过程中如何创建Action<T>

methodInfo.Invoke accepts arbitrary object parameters. methodInfo.Invoke接受任意对象参数。 Thus, the compiler cannot infer which concrete TMessage type you mean. 因此,编译器无法推断您指的是哪种具体的TMessage类型。

The solution is to specify it explicitly: 解决方案是显式指定它:

SubscribeToPublish((MyMessage o) => methodInfo.Invoke(pair.Value.Node, 
                                                      new object[] {o}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM