【问题标题】:Getting the name of [DataMember] in C#在 C# 中获取 [DataMember] 的名称
【发布时间】:2014-01-20 19:12:11
【问题描述】:

我有如下的模型类,

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

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

【问题讨论】:

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


【解决方案1】:

对您的课程稍作修改

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

【讨论】:

  • 好吧,GetProperties 适用于 WP7,你是对的。在不修改类的情况下,您可以使用它来获取所有成员,作为属性或字段:对于 WP7,var members = typeof(Station).GetMembers;。对于 WP8,var members = typeof(Station).GetTypeInfo().DeclaredMembers;
【解决方案2】:

我创建了一个扩展方法:

        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)))

【讨论】:

    【解决方案3】:

    您可以简单地使用Reflectioncast 将属性返回到DataMemberAttribute 类并读取名称property value

    Here 是一个完整的第 3 方示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 2012-02-02
      • 2016-01-04
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多