Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

c# - String interpolation issues

I'm trying to figure out why my unit test fails (The third assert below):

var date = new DateTime(2017, 1, 1, 1, 0, 0);

var formatted = "{countdown|" + date.ToString("o") + "}";

//Works
Assert.AreEqual(date.ToString("o"), $"{date:o}");
//Works
Assert.AreEqual(formatted, $"{{countdown|{date.ToString("o")}}}");
//This one fails
Assert.AreEqual(formatted, $"{{countdown|{date:o}}}");

AFAIK, this should work correctly, but it appears that it doesn't pass the formatting parameter in correctly, it it appears as just {countdown|o} to the code. Any idea why this is failing?

question from:https://stackoverflow.com/questions/42142003/string-interpolation-issues

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem with this line

Assert.AreEqual(formatted, $"{{countdown|{date:o}}}");

is that you have 3 curly quotes after the format string of the variable to be escaped and it starts escaping from left to right, therefore it treats the first 2 curly quotes as part of the format string and the third curly quote as the closing one.

So it transforms o in o} and the it's unable to interpolate it.

This should work

Assert.AreEqual(formatted, $"{{countdown|{date:o}"+"}");

Notice that the simpler $"{date}}}" (i.e. 3 curls after the variable without a format string) does work because it recognizes that the first curly quote is the closing one, while the interpretation of the format specifier after the : breaks the correct closing parenthesis identification.

To prove that the format string is escaped like a string, consider that the following

$"{date:x6f}"

is treated as

$"{date:o}"

Finally, it is perfectly possible that the double escaped curly quotes are part of a custom date format, so it is absolutely reasonable the behaviour of the compiler. Again, a concrete example

$"{date:MMM}}dd}}yyy}" // it's a valid feb}09}2017

Parsing is a formal process based on expression grammar rules, can't be done by just glancing at it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[2] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...