c# - 在 C# 中获取 [DataMember] 的名称

标签 c# .net windows-phone-7

我有如下的模型类,

public class Station
{
    [DataMember (Name="stationName")]
    public string StationName;
    [DataMember (Name="stationId")]
    public string StationId;
}

我想用属性名称获取 DataMember 的名称,即如果我有属性名称“StationName”,我如何获取 stationName

最佳答案

对你的类(class)稍作修改

[DataContract]
public class Station
{
    [DataMember(Name = "stationName")]
    public string StationName { get; set; }
    [DataMember(Name = "stationId")]
    public string StationId { get; set; }
}

这就是你得到它的方法

 var properties = typeof(Station).GetProperties();
 foreach (var property in properties)
 {
    var attributes = property.GetCustomAttributes(typeof(DataMemberAttribute), true);
     foreach (DataMemberAttribute dma in attributes)
     {
         Console.WriteLine(dma.Name);
      }                
  }

关于c# - 在 C# 中获取 [DataMember] 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20898181/

相关文章:

windows-phone-7 - Windows Phone - 为 PhoneApplicationPage 使用通用类

c# - XML 持续更新值

c# - 如何在 Azure 函数的堆栈跟踪中显示文件名和行号

asp.net - 何时在 ASP.NET MVC 应用程序生命周期中处置静态资源

c# - Entity Framework 还是其他?

windows-phone-7 - 如何使用App.xaml资源中定义的Popup?

c# - System.IO.File.OpenRead 工作但 System.IO.FileStream 不工作?

c# - 如何检测滚动矩形是否接近底部?

c# - 弹道库

c# - Silverlight 与 XNA 对比纯 HTML5