C 中 的用法

2021-06-17 16:49:29 字數 3853 閱讀 6512

一 字串中的用法

1。地球人都知道 c# 中 字串常量可以以 @ 開頭聲名,這樣的優點是轉義序列「不」被處理,按「原樣」輸出,即我們不需要對轉義字元加上 \ (反斜扛),就可以輕鬆coding。如,

c# code?

1

stringfilepath =@"c:\docs\source\a.txt"// rather than "c:\\docs\\source\\a.txt"

2。如要在乙個用 @ 引起來的字串中包括乙個雙引號,就需要使用兩對雙引號了。 這時候你不能使用 \ 來轉義爽引號了,因為在這裡 \ 的轉義用途已經被 @  「遮蔽」掉了。如,

c# code?

1

@"""ahoy!"" cried the captain."// 輸出為: "ahoy!" cried the captain.

有點像sql中的單引號常量處理方式:

c# code?

1

2

declare @msg varchar(100)

set @msg =''ahoy!''cried the captain.'  -- 輸出為: 'ahoy!' cried the captain.

3。@ 會識別換行符 其實這個特性,我不知道怎麼描述,只是偶然發現的,先看下面的**吧:

c# code?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

stringscript =@"

";

安逸吧,在cs檔案中寫js,結構就很清晰了,正常情況我們是這樣coding的:

stringscript2 =

"";

// or

stringscript3 =

"";

通常我們會選擇後者,因為js**一般比較長,或者方法體很大,或者需要連線其他變數,這樣結構比較清晰。 注意:如果「拼接」的次數很多,應該考慮使用stringbuilder了,有助於提高效能。 還有一種場景,也很常見,在程式中拼接 sql 語句,如

c# code?

1

2

3

privateconststringsql_ins_user =@"

insert into t_user([username], [password], email)

values(@username, @password, @email)";

哈哈,這樣就像寫儲存過程一般,保持相當高的**清晰度。 然而,我們需要關注乙個問題:字串長度 看下面的測試**:

c# code?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

privateconststringsql_ins_user1 =@"

insert into t_user([username], [password], email)

values(@username, @password, @email)";

privateconststringsql_ins_user2 =@"insert into t_user([username], [password], email)

values(@username, @password, @email)";

privateconststringsql_ins_user3 =@"insert into t_user([username], [password], email) values(@username, @password, @email)";

staticvoidmain(stringargs)

可以看到三個字串長度分別相差了,14=126-112和26=112-86,注意觀察了,在**編輯器中,sql_ins_user1 中第乙個換行符號之後,我縮排13個空格(insert之前),而 sql_ins_user2 中第乙個換行符號之後,我縮排25個空格(values之前), 那麼,加上乙個換行符,剛剛好 14和26 my god! 如此編寫**,雖然提高了**的清晰度和簡便性,卻無行中帶來了另乙個問題:字元長度! 很多場景下我們希望字串越短越好,如,通過ado.net 傳送 sql 語句給資料庫執行。 所以還是慎用之! 

二 識別符號中的用法

在 c#  規範中, @  可以作為識別符號(類名、變數名、方法名等)的第乙個字元,以允許c# 中保留關鍵字作為自己定義的識別符號。 如 class @class     } class class1 } 注意,@ 雖然出現在識別符號中,但不作為識別符號本身的一部分。 因此,以上示例,定義了乙個名為 class 的類,幷包含乙個名為 static 的方法,以及乙個引數名為了 bool 的形參。 這樣,對於跨語言的移植帶來了便利。因為,某個單詞在 c#  中作為保留關鍵字,但是在其他語言中也許不是。

具體見 c# language specification 2.4.2 identifiers 

c 中 的用法

c 中的 至少有以下幾種作用 1.忽略轉義字元 例如 string filename d 文字檔案 text.txt 使用 後 string filename d 文字檔案 text.txt 2.讓字串跨行 例如 string strsql select from humanresources.em...

c 中 的用法

從這個帖子開始記錄一下我學習和工作當中遇到的問題,以及解決方法等等。最經公司需要對於乙個c 做的瀏覽器外掛程式做維護,使得以前沒接觸過c 的我遇到了一大堆問題,在這記錄下c 中 的用法 是運算子中等級最高的,它分為三種 1 global scope 全域性作用域符 用法 name 2 class s...

C 中 的用法

一 字串中的用法 1。地球人都知道 c 中 字串常量可以以 開頭聲名,這樣的優點是轉義序列 不 被處理,按 原樣 輸出,即我們不需要對轉義字元加上 反斜扛 就可以輕鬆coding。如,c code?1 stringfilepath c docs source a.txt rather than c ...