Is there any way to convert an existing Func delegate to a string like that:
Func<int, int> func = (i) => i*2;
string str = someMethod(func); // returns "Func<int, int> func = (i) => i*2"
or at least smth close to it
Is there any way to convert an existing Func delegate to a string like that:
Func<int, int> func = (i) => i*2;
string str = someMethod(func); // returns "Func<int, int> func = (i) => i*2"
or at least smth close to it
I found a similar question here. It more or less boils down to:
By @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))
It doesn't return the Func<int, int> func = (i) =>
part like in your question, but it does get the underlying expression!
© 2022 - 2024 — McMap. All rights reserved.
Delegate
as anExpression
. See this question for details on how to extract lambda body as strings. – Cooperation