2015-11-30 66 views
0
using (var streamWriter = new StreamWriter(SomeRequest.GetRequestStream())) 
{ 
    string json = JsonConvert.SerializeObject(new 
    { 
     Type_member1 = "StacOverFlow", 
     Type_member2 = sometext, 
     Type_member3 = 0, 
     private = true 
    }); 
    streamWriter.Write(json); 
} 

正如您所見,存在名爲「private」的Type成員。當然,當我鍵入它,一條消息會彈出,告訴我:C#WPF「private」匿名類型成員

"Invalid expression term 'private'"

把「私人」內部報價將返回該錯誤:

"Invalid anonymous type member declarator. bla bla bla..."

是否有解決此問題的方法?

+1

你爲什麼不改變它是'Private'那麼因爲C#是區分大小寫的 – MethodMan

+0

@MethodMan THX你的建議,但我認爲user2864740的回答是最好的解決辦法:) – Wahyu

回答

2

private是C#框架的保留關鍵字,不能用作程序中的標識符。如果你試圖編寫string private = "sometext";那麼編譯器會通過自己的說明Identifier 'private' is a keyword來拋出異常。 所以你應該定義道具名稱爲@private

或者你應該通知序列化在序列化時將其命名爲私有。

+0

Thx,我用@private,現在工作:) – Wahyu

6

這可以通過使用語法來解決:

@private = true, 

注意使用@privatewhere the @ changes how the compiler interprets the source code)的;以及改變;,以避免其它語法錯誤

Keywords [ie. private ] are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if [ie. @private ] is a valid identifier but if [ie. private ] is not because if is a keyword.

替代。 ,創建一個非匿名類型(具有更好的代碼友好的成員名稱)並應用[JsonProperty][DataMember]屬性將序列化名稱更改爲'private'。

+1

由於這你的答案是與上述相同的一個,所以我選擇他的答案,因爲他先回答。對不起:) btw thx的答案! – Wahyu