【发布时间】: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