作为方法参数接受任何方法

本文关键字:方法 任何 参数 | 更新日期: 2023-09-27 18:05:27

我需要创建一个方法来动态检查作为参数传递的方法委托。但是我不能强迫表达式树接受任何方法,不管它们的签名是什么。

这是我的方法(不编译:error CS0030: Cannot convert type 'method' to 'Delegate')

public void Examine<T>(Expression<Func<T, Delegate>> expression2)
{
   // examine expression tree to get method name (MethodInfo)
}

我想这样调用它:

Examine<Foo>(x => foo1.Test1);
Examine<Bar>(x => bar2.DifferentMethod2);
// etc, with other methods

地点:

  • 类Foo有方法:bool Test1(int num)
  • 类栏有方法:'string DifferentMethod2(字符串a,字符串b) '
  • 和许多其他

如何实现?

备注:

  • 我不能使用Func<>或Action<>,因为将有许多可能的方法签名需要接受我没有引用的参数类型。

作为方法参数接受任何方法

您必须使用FuncAction,但是您可以在调用方而不是方法端使用它,因此您仍然可以接受任何类型。

static void Main()
{
    Foo foo1 = null;
    Bar bar2 = null;
    Examine<Foo>(x => (Func<int,bool>)foo1.Test1);
    Examine<Bar>(x => (Func<string,string,string>)bar2.DifferentMethod2);
}
public static void Examine<T>(Expression<Func<T, Delegate>> expression2)
{
    // examine expression tree to get method name (MethodInfo)
}

创建一个像

这样的表达式
.Lambda #Lambda1<System.Func`2[SandboxConsole.Foo,System.Delegate]>(SandboxConsole.Foo $x) {
    (System.Func`2[System.Int32,System.Boolean]).Call .Constant<System.Reflection.MethodInfo>(Boolean Test1(Int32)).CreateDelegate(
        .Constant<System.Type>(System.Func`2[System.Int32,System.Boolean]),
        .Constant<SandboxConsole.Program+<>c__DisplayClass0_0>(SandboxConsole.Program+<>c__DisplayClass0_0).foo1)
}

.Lambda #Lambda1<System.Func`2[SandboxConsole.Bar,System.Delegate]>(SandboxConsole.Bar $x) {
    (System.Func`3[System.String,System.String,System.String]).Call .Constant<System.Reflection.MethodInfo>(System.String DifferentMethod2(System.String, System.String)).CreateDelegate(
        .Constant<System.Type>(System.Func`3[System.String,System.String,System.String]),
        .Constant<SandboxConsole.Program+<>c__DisplayClass0_0>(SandboxConsole.Program+<>c__DisplayClass0_0).bar2)
}