嗨大家我有一个非常简单的类叫做人.
public class Person{
[DataMember(Name="MyName")]
public string Name { get;set;}
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试序列化或反序列化,一切都很好.在XML中,我可以看到一个名为"MyName"的标签,在我使用VS Intellisense看到的一个名为Name的属性中.我现在需要的是从对象访问属性的序列化名称.例如,我可以做这个对象.GetType().GetProperty("Name"); 但是如果我尝试做这个对象.GetType().GetProperty("MyName")反射说该属性不存在.我如何阅读该属性的序列化名称?有办法吗?
似乎唯一的方法是使用反射来访问属性的属性,如下所示:
var att = myProperty.GetType().GetAttributes();
var attribute = property.GetCustomAttributes(false)[0] as DataMemberAttribute;
Console.WriteLine(attribute.Name);
Run Code Online (Sandbox Code Playgroud)
这适用于客户端和服务器,无需序列化和反序列化对象。
| 归档时间: |
|
| 查看次数: |
2196 次 |
| 最近记录: |