Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create delegate via reflection

Given an assembly that contains

namespace Foo{public class Bar;}

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

like image 656
dss539 Avatar asked Jun 11 '10 15:06

dss539


1 Answers

If you use

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

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...

like image 160
Ruben Avatar answered Sep 19 '22 10:09

Ruben