C#属性命名事件 [英] C# Property Named Event
问题描述
我使用JSON序列化,并需要绑定到一个名为事件当然,事件的属性名是在C#中的关键字,这样做的东西,如字符串事件{搞定;组; }
是不允许的。反正是有去这样做呢?我不能改变回来给我对象的名称。
I am using Json serializer and need to bind to a property name called 'event' Of course event is a keyword in C#, so doing something such as string event { get; set; }
is not allowed. Is there anyway to go about doing that? I can't change the name of the object coming back to me.
推荐答案
假设你正在使用Json.NET,你可以使用 JsonProperty
属性,或 @
符号,或用 ContractResolver
(有一个内置的一个使事情驼峰,所以事件
的属性名称将序列化到事件
)。
Assuming you're using Json.NET, you can use the JsonProperty
attribute, or the @
symbol, or with a ContractResolver
(there's a built-in one that makes things camelCase, so a property name of Event
would serialize to event
).
[JsonProperty("event")]
public string Event { get; set; }
public string @event { get; set; }
public string Event { get; set; }
var s = JsonConvert.SerializeObject(myObj, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
这篇关于C#属性命名事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!