2017-04-11 37 views
1

我使用T4(C#)在運行時生成一些代碼。然後我將生成的代碼存儲在另一個模板的一部分的字符串中。在最終模板的相關代碼看起來像這樣:T4模板C# - 保持與 n r ..在生成的代碼中的常規字符串

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}"; 

誰能幫助我?

+0

我不知道是什麼類型'TransformText()'收益,但有可能使用'temp.TransformText()更換。 (Environment.NewLine,「\\ r \\ n」);' –

+0

@GrantWinney它的工作原理,thanks.TransformText返回一個字符串。我不認爲這是如此簡單......您能否請您重新發布您的評論作爲答案? – Malick

+0

好聽@Malick!完成。 –

回答

1

轉義\r\n字符應該工作。試試這個:

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

使用逐字符號的作品,以及:@"\r\n"