我有如下的模型类,
public class Station
{
[DataMember (Name="stationName")]
public string StationName;
[DataMember (Name="stationId")]
public string StationId;
}
我想获取具有属性名称的DataMember
的名称,即如果我有属性名称“StationName”,我如何获得stationName
?
答案 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
类属性的DataMemberAttribute
,cast
并阅读名称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)))