2015-11-30 70 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