You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何获取对象属性的XmlAttribute特性中AttributeName属性的值

解决方案

问题原因

GetCustomAttributes(true)返回的是object[]类型,编译期变量类型为object,所以无法直接访问XmlAttributeAttribute特有的AttributeName属性,需要先转换为强类型的特性实例。

实现步骤

  1. 引入必要命名空间
using System.Reflection;
using System.Xml.Serialization;
  1. 获取强类型特性实例
    有两种常用写法:
  • 泛型方法(推荐,.NET Framework 4.5+、.NET Core/.NET 全版本支持)
// 获取Rate类的Code属性
PropertyInfo codeProp = typeof(Rate).GetProperty(nameof(Rate.Code));
// 直接获取XmlAttributeAttribute特性实例
XmlAttributeAttribute attr = codeProp?.GetCustomAttribute<XmlAttributeAttribute>();
// 访问AttributeName属性
if (attr != null)
{
    string attributeName = attr.AttributeName; // 此处拿到的值就是roomcode
}
  • 兼容旧版本.NET的写法
object[] attrs = typeof(Rate).GetProperty("Code").GetCustomAttributes(true);
foreach (object attr in attrs)
{
    if (attr is XmlAttributeAttribute xmlAttr)
    {
        string attributeName = xmlAttr.AttributeName;
    }
}

单元测试示例(以xUnit为例)

public class RateXmlAttributeTests
{
    [Fact]
    public void CodeProperty_HasCorrectXmlAttributeName()
    {
        // 1. 获取属性元数据
        PropertyInfo codeProperty = typeof(Rate).GetProperty(nameof(Rate.Code));
        Assert.NotNull(codeProperty);
        
        // 2. 获取XmlAttribute特性
        XmlAttributeAttribute xmlAttr = codeProperty.GetCustomAttribute<XmlAttributeAttribute>();
        Assert.NotNull(xmlAttr);
        
        // 3. 验证属性名匹配预期
        Assert.Equal("roomcode", xmlAttr.AttributeName);
    }
}

内容的提问来源于stack exchange,提问作者Samuel8000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:06:03