在字符串中间插值
Interpolation in the middle of a string
我想在字符串中间插值,但是我不能使用String.Format
,因为字符串包含{}
大括号
这是我目前尝试过的方法:
string code = "(function(){var myvariable = $"{variableToBeInterpolated}"});"
Returns: ) expected ; expected
编辑: 我试过下面的代码片段,插值现在可以工作了,但是代码没有在浏览器中执行。
"(function(){var myvariable=" + $"{myvariable c#}" + ")});"
为什么要插在中间,不如把$
放在前面。对于 {
,您需要使用 {{
。 (}
同理)
string code = $"(function(){{ var myvariable = {myvariable} }});";
你试过了吗:
string someVariable = "test";
string code = $"(function()'{{var myvariable = ({someVariable} in c#)}});"
在C#中使用$是字符串插值。在 C# 6 中添加
一般信息
在 C# 版本 6 中,语言中添加了广泛的 string interpolation capabilities。
String interpolation provides a more readable and convenient syntax to
create formatted strings than a string composite formatting feature.
要解决您的问题,请查看文档的 special characters 部分,内容如下:
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}".
例子
var variable = 10;
var code = $"(function() {{ var myVariable = {variable} }});";
Console.WriteLine(code);
Output: (function() { var myVariable = 10 });
我想在字符串中间插值,但是我不能使用String.Format
,因为字符串包含{}
大括号
这是我目前尝试过的方法:
string code = "(function(){var myvariable = $"{variableToBeInterpolated}"});"
Returns: ) expected ; expected
编辑: 我试过下面的代码片段,插值现在可以工作了,但是代码没有在浏览器中执行。
"(function(){var myvariable=" + $"{myvariable c#}" + ")});"
为什么要插在中间,不如把$
放在前面。对于 {
,您需要使用 {{
。 (}
同理)
string code = $"(function(){{ var myvariable = {myvariable} }});";
你试过了吗:
string someVariable = "test";
string code = $"(function()'{{var myvariable = ({someVariable} in c#)}});"
在C#中使用$是字符串插值。在 C# 6 中添加
一般信息
在 C# 版本 6 中,语言中添加了广泛的 string interpolation capabilities。
String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature.
要解决您的问题,请查看文档的 special characters 部分,内容如下:
To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}".
例子
var variable = 10;
var code = $"(function() {{ var myVariable = {variable} }});";
Console.WriteLine(code);
Output:
(function() { var myVariable = 10 });