WCF Read DataMember Name attribute
I have a very simple class called person.
public class Person{
[DataMember(Name="MyName")]
public string Name { get;set;}
}
If I try to serialize or de-serialize, everything works great. In the XML I can see a tag called "MyName" and in t开发者_运维问答he object I see with the VS Intellisense a property called Name.
What I need now is to access, from the object, the serialized name of the property.
For example, I can do object.GetType().GetProperty("Name");
but if I try to do object.GetType().GetProperty("MyName")
, the reflection says that the property does not exist. How I can read the serialized name of the property? Is there a way?
It seems that the only way is to access, using reflection, the attributes of the property in this way:
var att = myProperty.GetType().GetAttributes();
var attribute = property.GetCustomAttributes(false)[0] as DataMemberAttribute;
Console.WriteLine(attribute.Name);
This works on both, client and server, without the need of serialize and deserialize the object.
精彩评论