C#中具有可变内容的字符串插值

编程入门 行业动态 更新时间:2024-10-22 11:13:49
本文介绍了C#中具有可变内容的字符串插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可以将字符串的模板存储在变量中并对其进行插值吗?

Can one store the template of a string in a variable and use interpolation on it?

var name = "Joe"; var template = "Hi {name}";

然后我想做类似的事情:

I then want to do something like:

var result = $template;

原因是我的模板来自数据库。

The reason is my templates will come from a database.

推荐答案

这可以按照要求使用动态编译完成,例如通过 Microsoft.CodeAnalysis.CSharp.Scripting 包。例如:

This can be done as requested using dynamic compilation, such as through the Microsoft.CodeAnalysis.CSharp.Scripting package. For example:

var name = "Joe"; var template = "Hi {name}"; var result = await CSharpScript.EvaluateAsync<string>( "var name = \"" + name + "\"; " + "return $\"" + template + "\";");

请注意,这种方法很慢,您需要添加更多逻辑来处理转义(和注入攻击)在字符串中,但以上内容只是概念验证。

Note that this approach is slow, and you'd need to add more logic to handle escaping of quotes (and injection attacks) within strings, but the above serves as a proof-of-concept.

更多推荐

C#中具有可变内容的字符串插值

本文发布于:2023-11-08 14:02:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   插值   内容

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!