[英]Displaying FQN in Expression.Call
我試圖獲取使用表達式樹創建的靜態方法調用的字符串表示形式。 但是,文本表示形式不包含方法調用的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()
{
}
}
}
string.Format("{0}.{1}", method.DeclaringType.Name, method.Name)
如果(根據對Q的最新編輯)希望將表達式轉換為可執行文件,則可以執行以下操作:
Action compiled = Expression.Lambda<Action>(call2).Compile();
然后,您可以像調用其他任何Action一樣調用已編譯的表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.