gpt4 book ai didi

c# - 动态字符串插值

转载 作者:可可西里 更新时间:2023-11-01 08:15:55 25 4
gpt4 key购买 nike

谁能帮我解决这个问题?

必需的输出:“管理员的待办事项

class Program
{
static void Main(string[] args)
{
Console.WriteLine(ReplaceMacro("{job.Name} job for admin", new Job { Id = 1, Name = "Todo", Description="Nothing" }));
Console.ReadLine();
}

static string ReplaceMacro(string value, Job job)
{
return value; //Output should be "Todo job for admin"
}
}

class Job
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}

最佳答案

两个建议:

DataBinder.Eval

string ReplaceMacro(string value, Job job)
{
return Regex.Replace(value, @"{(?<exp>[^}]+)}", match => {
return (System.Web.UI.DataBinder.Eval(new { Job = job }, match.Groups["exp"].Value) ?? "").ToString();
});
}

Linq.Expression

使用 MSDN LINQSamples 中提供的动态查询类:

string ReplaceMacro(string value, Job job)
{
return Regex.Replace(value, @"{(?<exp>[^}]+)}", match => {
var p = Expression.Parameter(typeof(Job), "job");
var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, match.Groups["exp"].Value);
return (e.Compile().DynamicInvoke(job) ?? "").ToString();
});
}

在我看来,Linq.Expression 更强大,所以如果您信任输入的字符串,您可以做更多有趣的事情,即:

value = "{job.Name.ToUpper()} job for admin"
return = "TODO job for admin"

关于c# - 动态字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874172/

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