gpt4 book ai didi

c# - 将 Func 委托(delegate)转换为字符串

转载 作者:太空狗 更新时间:2023-10-29 21:44:20 27 4
gpt4 key购买 nike

有什么方法可以将现有的 Func 委托(delegate)转换为这样的字符串:

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

或者至少接近于它

最佳答案

我找到了 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) =>部分像你的问题,但它确实得到了潜在的表达!

关于c# - 将 Func 委托(delegate)转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29067873/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com