【问题标题】:ExpressionTree as method parameter to accept any methodExpressionTree 作为方法参数接受任何方法
【发布时间】:2016-09-01 20:15:26
【问题描述】:

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

这是我的方法(无法编译: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)
  • 类 Bar 有方法:'string DifferentMethod2(string a, string b)`
  • 还有许多其他

如何实现?

备注:

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

【问题讨论】:

  • 没测试过,但是func或者action是动态的?像鸭子一样的嘎嘎声

标签: c# lambda expression-trees


【解决方案1】:

您必须使用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)
}

对于两个调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2012-03-18
    相关资源
    最近更新 更多