Create delegate via reflection

后端 未结 2 1365
感动是毒
感动是毒 2021-01-18 10:28

Given an assembly that contains

namespace Foo{public class Bar;}

How could I create an Action from another asse

2条回答
  •  没有蜡笔的小新
    2021-01-18 10:53

    If you use

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

    actionType will now represent Action. 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...

提交回复
热议问题