我有如下所示的模型类,
public class Station
{
[DataMember (Name="stationName")]
public string StationName;
[DataMember (Name="stationId")]
public string StationId;
}
我想获取
DataMember
的名称和属性名称,即如果我有属性名称“StationName”,我怎样才能获得 stationName
?
对你的课程稍作修改
[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);
}
}
我创建了一个扩展方法:
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)))
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;
}
}