C#如何获取对象XMLAttribute的AttributeName的值

How to get the value of AttributeName of XMLAttribute of object C#

我想使用反射来获取 XMLAttribute 的 AttributeName。

public class Rate{
    [XmlAttribute(AttributeName = "roomcode")]
    public string Code { get; set; }
}

当我这样做时:

var rate = typeof(Rate).GetProperty("Code").GetCustomAttributes(true);

我可以看到属性名称为“roomcode”的对象率 属性,但无论我尝试什么,我似乎都无法访问它。

我想进行单元测试,将我的对象的属性名称与 xml 节点的属性名称进行比较。

GetCustomAttributes returns 和 object[],因此您需要转换为 XmlAttributeAttribute 才能访问 AttributeName 属性.

一种方法是使用 LINQ CastSingle:

var rate = typeof(Rate)
    .GetProperty("Code")
    .GetCustomAttributes(true)
    .Cast<XmlAttributeAttribute>()
    .Single()
    .AttributeName;

但是使用GetCustomAttribute<T>扩展方法会更简洁,它获取给定类型的单个属性T:

var rate = typeof(Rate)
    .GetProperty("Code")
    .GetCustomAttribute<XmlAttributeAttribute>(true)
    .AttributeName;

顺便说一句,您还可以在获取 PropertyInfo 时使用 nameof 来提高类型安全性:

var rate = typeof(Rate)
    .GetProperty(nameof(Rate.Code))
    .GetCustomAttribute<XmlAttributeAttribute>(true)
    .AttributeName;