将Func委托转换为字符串

cur*_*ous 6 c# delegates func

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

Func<int, int> func = (i) => i*2;
string str = someMethod(func); // returns "Func<int, int> func = (i) => i*2"
Run Code Online (Sandbox Code Playgroud)

或者至少接近它

小智 5

我在这里找到了一个类似的问题。它或多或少归结为:

通过@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))
Run Code Online (Sandbox Code Playgroud)

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

  • 不幸的是,问题是将 Func 转换为字符串而不是上面的表达式。 (2认同)

归档时间:

查看次数:

2052 次

最近记录:

7 年,10 月 前