将Func委托转换为字符串

时间:2015-03-16 00:20:49

标签: c# delegates func

有没有办法将现有的Func委托转换为这样的字符串:

Func<int, int> func = (i) => i*2;
string str = someMethod(func); // returns "Func<int, int> func = (i) => i*2"

或至少接近它

1 个答案:

答案 0 :(得分:4)

我找到了a similar question here。它或多或少归结为:

通过@TheCloudlessSky,

Expression<Func<Product, bool>> exp = (x) => (x.Id > 5 && x.Warranty != false);

string expBody = ((LambdaExpression)exp).Body.ToString(); 
// Gives: ((x.Id > 5) AndAlso (x.Warranty != False))

var paramName = exp.Parameters[0].Name;
var paramTypeName = exp.Parameters[0].Type.Name;

// You could easily add "OrElse" and others...
expBody = expBody.Replace(paramName + ".", paramTypeName + ".")
             .Replace("AndAlso", "&&");


Console.WriteLine(expBody);
// Output: ((Product.Id > 5) && (Product.Warranty != False))

它不像你的问题那样返回Func<int, int> func = (i) =>部分,但确实得到了基础表达式!