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

问题描述 投票:0回答:4

我有如下所示的模型类,

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

我想获取

DataMember
的名称和属性名称,即如果我有属性名称“StationName”,我怎样才能获得
stationName

c# .net windows-phone-7
4个回答
16
投票

对你的课程稍作修改

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

3
投票

我创建了一个扩展方法:

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

1
投票

您可以简单地使用

Reflection
cast
将属性返回到
DataMemberAttribute
类并读取名称
property value

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


0
投票
public static class TypeExtensions
{

    /// <summary>
    /// Returns the nameofMember's DataMemberAttribute.Name
    /// Example usage:
    /// var aPropertyDataMemberName = typeof(MyType).GetDataMemberName(nameof(MyType.AProperty));
    /// </summary>
    /// <param name="type">The type. Example: typeof(MyType)</param>
    /// <param name="nameofMember">The member of the type. Example: nameof(MyType.AProperty)</param>
    /// <param name="throwIfMemberDoesntExist">Optionally throw if the member does not exist</param>
    /// <returns>nameofMember's DataMemberAttribute.Name
    /// </returns>
    /// <exception cref="ArgumentOutOfRangeException">Thrown if the member does not exist</exception>
    public static string? GetDataMemberName(this Type type, string nameofMember, bool throwIfMemberDoesNotExist = true)
    {
        MemberInfo? memberInfo = type?.GetProperty(nameofMember) ?? type?.GetField(nameofMember) ?? type?.GetMember(nameofMember)?.FirstOrDefault();
        string? ret = (memberInfo?.GetCustomAttribute(typeof(DataMemberAttribute), true) as DataMemberAttribute)?.Name ?? string.Empty;
        if (memberInfo == null && throwIfMemberDoesNotExist) { throw new ArgumentOutOfRangeException(nameof(nameofMember), "Member does not exist."); }
        return ret;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.