【问题标题】:T4 Template C# - Keep regular string with \n \r .. in the generated codeT4 模板 C# - 在生成的代码中使用 \n \r .. 保留常规​​字符串
【发布时间】:2017-04-11 13:04:18
【问题描述】:

我正在使用 T4 (C#) 在运行时生成一些代码。然后我将生成的代码存储在一个字符串中,该字符串是另一个模板的一部分。最终模板中的相关代码如下所示:

string myFinalString = @"<#=GetGeneratedCode()#>";

GetGeneratedCode() 在哪里:

public string GetGeneratedCode()
{
  MyTemplate temp = new MyTemplate (); //<- another T4 template
  return temp.TransformText();
}

MyTemplate.TransformText 返回类似于以下的代码:

MyClass
{
 int myVar1;
 string myVar2;
}

问题是在我生成的源文件中,字符串myFinalString 设置如下:

string myFinalString = @"MyClass
{
   int myVar1;
   string myVar2;
}";

为了可读性,我希望得到一个生成的常规字符串,如下所示:

string myFinalString = @"MyClass\r\n{\r\n int myVar1;\r\n string myVar2;\r\n}";

谁能帮我解决这个问题?

【问题讨论】:

  • @GrantWinney 它有效,谢谢。TransformText 返回一个字符串。我不认为这很简单......您能否将您的评论重新发布为答案?

标签: c# t4


【解决方案1】:

转义 \r\n 字符应该可以工作。试试这个:

public string GetGeneratedCode()
{
  MyTemplate temp = new MyTemplate (); //<- another T4 template
  return temp.TransformText().Replace(Environment.NewLine, "\\r\\n");
}

使用逐字符号也可以:@"\r\n"

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 1970-01-01
    • 2010-09-22
    • 2017-04-02
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多