开发者

Can I get DataMember names in the code?

开发者 https://www.devze.com 2023-03-05 13:06 出处:网络
in one project, I use datamember to serialize a class to an xml file, like, [DataMember] public string Member1;

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 i开发者_运维知识库t 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?


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.

static class SerializationConstants
{
  public static string MemberTag = "Member1"; //or "Member2"
}

Then in your datamember you can use the property with the Name attribute.

[DataMember(Name=SerializationConstants.MemberTag)
public string Member1;

That would control serialization such that in your code for querying the xml, you can do something like:

XmlNode1.SelectSingleNode(SerializationConstants.MemberTag)

It would be a hack but I guess it should do if I understood your question correctly.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消