是否可以在表达式代码为字符串的情况下实现打印输出表达式代码和值?
class MyClass
{
// Expected output
// 2 + 2 = 4
// v = 3
// Field = 5
// OtherClass.GetInfo() = Hello
// new OtherClass().OtherField = 22
//
void MyMethod()
{
Console.WriteLine(ExpressionPrintString("2 + 2"));
int v = 3;
Console.WriteLine(ExpressionPrintString("v"));
Console.WriteLine(ExpressionPrintString("Field"));
Console.WriteLine(ExpressionPrintString("OtherClass.GetInfo()"));
Console.WriteLine(ExpressionPrintString("new OtherClass().OtherField"));
}
int Field = 5;
}
class OtherClass
{
public static sting GetInfo() { return "Hello"; }
public int OtherField = 22;
}
我知道Expression<TDelegate>
允许为Lambda表达式执行此操作,如下所示:
// Usage: ExpressionPrintString(() => 2 + 2) // returns "2 + 2 = 4"
static string ExpressionPrintString(Expression<Func<object>> expr, string delimiter = " = ")
{
return expr.ToString().Replace("() => ","")
+ delimiter
+ expr.Compile().DynamicInvoke();
}
但它的输出有时并不漂亮,因为它返回表达式的内部表示。例如
protected override void OnPreRenderComplete(EventArgs e)
{
// In this context
// The following call:
string s = ExpressionPrintString(() => Context.Items["UrlRewrite:OriginalUrl"]);
// returned:
// value(ASP.default_aspx).Context.Items.get_Item("UrlRewrite:OriginalUrl") = http://localhost:8011/Companies
// The expected output would be
// Context.Items["UrlRewrite:OriginalUrl"] = http://localhost:8011/Companies
}