【问题标题】:Displaying FQN in Expression.Call在 Expression.Call 中显示 FQN
【发布时间】:2014-04-24 19:56:56
【问题描述】:

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

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

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

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

目标是将根表达式转换为我可以在内存中使用和编译的 C# 代码 sn-p。

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()
        {
        }
    }
}

【问题讨论】:

    标签: c# expression-trees


    【解决方案1】:
    string.Format("{0}.{1}", method.DeclaringType.Name, method.Name)
    

    如果(根据您最近对 Q 的编辑)您想将表达式转换为可执行文件,您可以改为执行以下操作:

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

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

    【讨论】:

    • 我不想仅仅获得一个方法的 FQN。目标是将根表达式转换为我可以在内存中使用和编译的 C# 代码。抱歉不清楚,请查看我对问题的修改。
    • 如果你想编译表达式以便能够调用它,那么你当然不想通过对表达式的 ToString() 调用。 Expression.Lambda() 和 Lambda.Compile() 是你的朋友
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多