C#中具有可变内容的字符串插值 [英] String Interpolation With Variable Content in C#

查看:64
本文介绍了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#中具有可变内容的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆