C#序列化 DataMember的Name属性意义(使用场景)

1. Name属性的意义

官方对于Name属性的解释:The Name property enables you to use names that are not permitted as common language runtime (CLR) identifiers. In addition, this property enables the type author to define a data member name separate from the CLR member name. This separate definition helps in versioning scenarios (changing the CLR member name without breaking the data contract) and allows a different naming convention for data contact members and CLR members.

简单来说,就是允许用户定义的序列化字段与API实际的字段名称不同,因为在实际场景中API的参数字段与C#代码的命名规范不一致,可能出现某一个字段的命名在API规范中可以,但是在C#中却不符合规范,例如:

API部分字段:

"RESUBMISSION": "00000000",
"/SAPF15/STATUS": "",
"PSOTY": "",

C#序列化字段定义代码:

[DataMember]
public string RESUBMISSION { set; get; }

[DataMember(Name = "/SAPF15/STATUS")]
public string SAPF15_STATUS {set;get;}

[DataMember]
public string PSOTY { set; get; }


上例中,API的字段“/SAPF15/STATUS”命名格式在C#中不可作为属性名称,因此需要DataMember的Name属性来使得两者之间分离,同时也为字段名变更提供了便利。

2. 参考资料

《What is the purpose of setting a DataMember Name [closed]》

 

暂无评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注