创建通过反射委托 [英] Create delegate via reflection

查看:107
本文介绍了创建通过反射委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于包含程序集

namespace Foo{public class Bar;}

我怎么能创建一个动作< Foo.Bar> 从没有在编译时引用的第一个组件的另一个组件

How could I create an Action<Foo.Bar> from another assembly without referencing the first assembly at compile time?

推荐答案

如果您使用

Type barType = Type.GetType("Foo.Bar, whateverassembly");
Type actionType = typeof(Action<>).MakeGenericType(barType);

操作类型现在将重新present 动作&LT; Foo.Bar&GT; 。但是,要使用它,你需要contintue使用反射,所以你需要找到一个的MethodInfo 适合签名无效( Foo.Bar)和呼叫 Delegate.CreateDelegate 来创建一个委托。你还需要 Delegate.DynamicInvoke 来执行它。

actionType will now represent Action<Foo.Bar>. However, to use it, you'll need to contintue to use reflection, so you'll need to find a MethodInfo that fits the signature void(Foo.Bar), and call Delegate.CreateDelegate to create a delegate. And you'll need Delegate.DynamicInvoke to execute it.

Delegate call = Delegate.CreateDelegate(actionType, ...);
...
call.DynamicInvoke(someBar);

有个声音告诉我,不是你想的是什么...

Something tells me that's not what you're thinking of...

这篇关于创建通过反射委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆