我可以在代码中获取 DataMember 名称吗?
在一个项目中,我使用 datamember 将类序列化为 xml 文件,例如,
[DataMember]
public string Member1;
稍后我查询 xml 以获取一个值,例如:
XmlNode1.SelectSingleNode("Member1");
是否可以将上面的 Member1
设为变量,以便当我将 DataMember
名称更改为 Member2
时,查询中的 Member1
可以自动更改为 Member2
,而不是比我手动更改它?
in one project, I use datamember to serialize a class to an xml file, like,
[DataMember]
public string Member1;
later I query the xml to get one value out, like:
XmlNode1.SelectSingleNode("Member1");
Is it possible that make the Member1
above to a variable so when I change the DataMember
name to be Member2
the Member1
in the query can be changed to Member2
automatically ,rather than I manually change it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不太确定我理解您希望实现的目标,但我想如果您希望能够集中控制序列化的输出,您可以在公共静态类中定义标签。
然后在您的数据成员中,您可以使用具有 Name 属性的属性。
这将控制序列化,以便在查询 xml 的代码中,您可以执行以下操作:
这将是一个 hack,但我想如果我正确理解您的问题,它应该可以。
I am not exactly sure I understand what you hope to achieve, but I am thinking if you want to be able to centrally control the output from the serialization, you could define the tag in say a public static class.
Then in your datamember you can use the property with the Name attribute.
That would control serialization such that in your code for querying the xml, you can do something like:
It would be a hack but I guess it should do if I understood your question correctly.
您应该在使用 XML 文件时反序列化它,然后您可以使用字段名称来访问属性,如果您进行重构,它们将会更改。
You should deserialize the XML file when working with it, then you can use field names to access properties and they would change if you would do refactoring.
这听起来不是一个好主意。
如果您担心类中的属性名称随 DataMember 属性发生变化,那么您可能需要在该类和 XML 查询之间采用 DTO 形式的抽象层。这样,您的 XML 查询类就不会关心该成员名称是否更改,因为您的 DTO 永远不会更改。只是从 DTO 到 volitle 类的映射。
This doesn't sound like a great idea.
If you are concerned about property names changing in your class with the DataMember attribute, you are probably going to want a layer of abstraction in the form of a DTO between that class and your XML querying. That way your XML querying class doesn't care if that member name changes or not because your DTO will never change. Just the mapping from the DTO to the volitle class.