C# Verbatim String Line Breaks: CRLF, CR, or LF?

你。 提交于 2019-12-10 14:01:14

问题


I ran into an interesting problem today where my tests were failing consistently on the build machine when they worked just fine on my machine even using the same configuration. When I looked at the differences output by Assert.AreEqual in the failure dump, I couldn't see anything different. After a bunch of investigation, I came to find out that the verbatim string in the test case source code (which spanned multiple lines) was using CRLF on my machine, but using LF on the build machine, causing comparisons of that string with a generated string to fail. The culprit turned out to be inconsistent Git settings on the two systems, with the build system automatically converting CRLF sequences to just LF.

Does the C# specification say anything about how line breaks in verbatim strings should be interpreted (perhaps using Environment.Newline, or at least something consistent)? This seems like a problem that could bite lots of people in very hard to diagnose and hard to fix ways, especially with .NET Standard. For example, if you have a .NET Standard project, and have team members on both Linux and Windows, this is likely to bite either the Linux team members or the Windows team members.


回答1:


The spec addresses this by not addressing it:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure

In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote_escape_sequence.

Since no exception is made for line endings, you get whatever line endings were used in the source file. As you found out.




回答2:


This solution based on the Git Help documentation may help ensure consistency regardless of each Git instance's setting.

As per the documentation in https://help.github.com/articles/dealing-with-line-endings/

Optionally, you can configure the way Git manages line endings on a per-repository basis by configuring a special .gitattributes file. This file is committed into the repository and overrides an individual's core.autocrlf setting, ensuring consistent behavior for all users, regardless of their Git settings.



来源:https://stackoverflow.com/questions/48196840/c-sharp-verbatim-string-line-breaks-crlf-cr-or-lf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!