【问题标题】:C# mutiline code string interpolation not working [closed]C#多行代码字符串插值不起作用[关闭]
【发布时间】:2020-10-15 21:22:37
【问题描述】:

我正在尝试将一些代码添加到这样的代码字符串中


        public static string Compile(string code)
        {
            Write("compiler called.");
/////////////Below is the string I want to interpolate//////////////
            
            string codeToCompile = $@"
            using System;

            namespace RoslynCompileSample
            {
                public class Writer
                {
                    public string Write()
                    {
                        
                        {code}
                    }
                }
            }";
///////////////// Other Codes...//////////////////////////

我尝试使用$@,但仍无法识别为字符串:

【问题讨论】:

  • 抱歉打错了,因为没有code 变量,code' 是方法的参数,让我来解决这个问题。
  • 为什么要使用内插字符串?您似乎不需要对该字符串进行插值,并且 C# 自然包含 { } 作为其范围的一部分这一事实意味着它破坏了您不需要的插值

标签: c# .net


【解决方案1】:

这里有两点要提:

  1. code 的分配不正确

  2. 您必须转义插值字符串中的 {} 字符(阅读文档的 special characters section
    (如果你也想使用" (在verbatim string@ 中,你也可以将它加倍到"" 得到一个),例如string code = @"Console.WriteLine(""Helloworld"");";

string code = "Console.WriteLine(\"Helloworld\");";
string codeToCompile = $@"using System;

namespace RoslynCompileSample
{{
    public class Writer
    {{
        public string Write()
        {{
            var code = {code}
        }}
    }}
}}";
猜你喜欢
  • 2013-01-04
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 2016-01-19
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
相关资源
最近更新 更多