在表达式中显示FQN.呼叫

本文关键字:FQN 呼叫 显示 表达式 | 更新日期: 2023-09-27 17:59:43

我正在尝试获取使用表达式树创建的静态方法调用的字符串表示。但是,文本表示不包含方法调用的FQN。下面给出的代码输出TestMethod(),而不是AnotherClass。我需要的TestMethod()

编辑:这只是一个简单的例子。最终输出可以是这样的:-

AnotherClass.TestMethod<Guid>("BLOB_DATA", new MyClass())

所以,我并不是想仅仅获得一个方法的FQN。根表达式对象甚至可能不是方法调用。我认为,无论表达式有多复杂,执行ToString()都会返回可以表示它的C#代码

目标是将根表达式转换为C#代码片段,以便在内存中使用和编译。

using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ExpressionTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // Variant 1
            MethodCallExpression call = Expression.Call(typeof (AnotherClass), "TestMethod", Type.EmptyTypes);
            Console.WriteLine(call.ToString());
            // Variant 2
            MethodInfo method = typeof (AnotherClass).GetMethod("TestMethod");
            MethodCallExpression call2 = Expression.Call(method);
            Console.WriteLine(call2.ToString());
            Console.ReadLine();
        }
    }
    internal class AnotherClass
    {
        public static void TestMethod()
        {
        }
    }
}

在表达式中显示FQN.呼叫

string.Format("{0}.{1}", method.DeclaringType.Name, method.Name)

如果(根据最近对Q的编辑)你想把表达式变成可执行的东西,你可以做一些事情,比如:

Action compiled = Expression.Lambda<Action>(call2).Compile();

然后,您可以像调用任何其他Action 一样调用编译后的表达式