Create delegate via reflection

后端 未结 2 1353
感动是毒
感动是毒 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:46

    You can't call it Action in your calling code, since you won't have access to that type definition if you don't reference it at compile time. Since Delegates are contravariant, you can return an Action and use that, or use Action where the IBar interface is defined in a referenced assembly, and implemented by Foo.Bar.

    If you do return an Action, you'd either have to use Foo.Bar members via reflection (or dynamic if using C# 4.0) or use cast it to Foo.Bar where the casting code has a reference to the assembly where Foo.Bar is defined.

    提交回复
    热议问题