How to begin "block of string" formatting in C#?
I have to write some queries in my C# code and had a question about formatting. See below:
string sql = "SELECT * ";
sql += "FROM HYT_User_Vehicle_Group_Assoc ";
sql += "INNER JOIN HYT_Vehicle_Group ON HYT_Vehicle_Group.Vehicle_Group_No = HYT_User_Vehicle_Group_Assoc.Vehicle_Group_No ";
Coming from PHP background, this is how I would have written it in PHP:
$sql = "SELECT *
FROM HYT_User_Vehicle_Group_Assoc
INNER JOIN HYT_Vehicle_Group ON HYT_Vehicle_Group.Vehicle_Group_No = HYT_User_Vehicle_Group_Assoc.Vehicle_Group_No";
notice how I don't have to always write a sql +=
for eac开发者_Go百科h new line in the string? Is there some wayto tell C# that I'm going to begin a "block of string", such that I don't have to always type sql +=
?
Yup - use a verbatim string literal by putting @ before the leading ":
string sql = @"SELECT *
FROM HYT_User_Vehicle_Group_Assoc
INNER JOIN HYT_Vehicle_Group
ON HYT_Vehicle_Group.Vehicle_Group_No = HYT_User_Vehicle_Group_Assoc.Vehicle_Group_No";
Note that this also removes escaping with a backslash - one of the times it's really useful is for regular expressions and Windows file paths. To include a double-quote in a verbatim string literal, you double it:
string text = "Jon says, ""Verbatim string literals."" And that's all.";
For particularly large blocks of code-as-text, I'd probably stick them in a separate embedded resource, mind you - or use an ORM so I didn't need SQL for the majority of data access :)
For more on strings, string literals (regular and verbatim), escape sequences etc, see my article on the topic.
@"Try
this!"
At-sign :) Will do what you want.
You can consider using @ attribute for strings spanning multiple lines. Refer this link for more details on usage.
sql = @"SELECT *
FROM HYT_User_Vehicle_Group_Assoc
INNER JOIN HYT_Vehicle_Group ON HYT_Vehicle_Group.Vehicle_Group_No = HYT_User_Vehicle_Group_Assoc.Vehicle_Group_No";
See http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
Verbatim String Literals.
@"Here is my
multiline verbatim string"
精彩评论