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

时间:2014-01-03 06:48:24

标签: c# .net windows-phone-7

我有如下的模型类,

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

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

3 个答案:

答案 0 :(得分:7)

稍微修改一下你的课程

[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);
      }                
  }

答案 1 :(得分:1)

您只需使用返回Reflection类属性的DataMemberAttributecast并阅读名称property value即可。

Here是完整的第三方示例。

答案 2 :(得分:0)

我创建了一个扩展方法:

        public static string GetDataMemberName(this MyClass theClass, string thePropertyName)
    {
        var pi = typeof(MyClass).GetProperty(thePropertyName);
        if (pi == null) throw new ApplicationException($"{nameof(MyClass)}.{thePropertyName} does not exist");
        var ca = pi.GetCustomAttribute(typeof(DataMemberAttribute), true) as DataMemberAttribute;
        if (ca == null) throw new ApplicationException($"{nameof(MyClass)}.{thePropertyName} does not have DataMember Attribute"); // or return thePropertyName?
        return ca.Name;
    }

随用法

myInstance.GetDataMemberName(nameof(MyClass.MyPropertyName)))