开发者

WCF Read DataMember Name attribute

开发者 https://www.devze.com 2022-12-17 12:51 出处:网络
I have a very simple class called person. public class Person{ [DataMember(Name="MyName")] public string Name { get;set;}

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.

0

精彩评论

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

关注公众号