C# – 如何在变量名中使用无效字符
在C#中,我正在构建一个类(这里为了讨论目的而简化),最终将序列化为一些外部定义的JSON:
{ "$schema": "https://example.com/person.json", "name": "John", "age": 86 }
在我的代码中我会有类似的东西:
public class Person { public const string $schema= @"https://example.com/person.json"; public string name {get;set; } public int age {get; set;} }
…
Person person = new Person(); person.name = "John"; person.age = 88; JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(person);
在上面的代码中,$ schema导致出现“意外字符’$’错误。是否有解决方法?
将属性[DataContract]
提供给Person
类。
另外,你的意思是使schema
const
?
[DataContract] public class Person { [DataMember(Name = "$schema")] public string schema { get; set; } public string name { get; set; } public int age {get; set;} }
如果使用JSON.NET,则可以使用JsonProperty
属性:
上述就是C#学习教程:C# – 如何在变量名中使用无效字符分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public class Person { [JsonProperty(PropertyName = "$schema")] public string schema {get; set;} = @"lsjdhflsjkdf"; public string name {get;set;} }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/954038.html