简体   繁体   中英

How to write a string that starts with @ and contains “ ” in C#

When I change the following C# string

string xml="xmlns:qtpRep=\"http://www.mercury.com/qtp/ObjectRepository\""

into

string xml=@"xmlns:qtpRep=\"http://www.mercury.com/qtp/ObjectRepository\""

I get compiler error: ;expected
How can I express the literal double quotes inside a string starting with @ ?

You double the double quotes instead of using a backslash:

string xml = @"xmlns:qtpRep=""http://www.mercury.com/qtp/ObjectRepository""";

(See MSDN for more details.)

Although in this case it's not clear why you want a verbatim string literal anyway... and for XML attributes it's generally simpler just to use single quotes:

string xml = @"xmlns:qtpRep='http://www.mercury.com/qtp/ObjectRepository'";

I'm also bound to say that if you're creating XML strings yourself, you're probably Doing It Wrong TM . Use an XML API instead :)

Two double quotes translate to a single quote when the string is verbatim (with @ ).

For example:

Console.WriteLine(@"this is ""enclosed in double quotes""");

...will write:

this is "enclosed in double quotes"

将它们加倍:

 string xml = @"xmlns:qtpRep=\""http://www.mercury.com/qtp/ObjectRepository\""";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM