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

如何获取C#对象中属性的自定义Header特性值列表?

实现GetAttributes方法的解决方案

要实现这个方法,核心是借助C#的反射机制读取属性上的自定义特性,具体步骤和代码如下:

方法实现

using System;
using System.Collections.Generic;
using System.Reflection;

public static List<string> GetAttributes(object obj)
{
    var headerNames = new List<string>();
    if (obj == null) return headerNames;

    // 获取对象的类型
    Type type = obj.GetType();
    // 获取所有公共属性
    PropertyInfo[] properties = type.GetProperties();

    foreach (var property in properties)
    {
        // 获取当前属性上的Header特性
        var headerAttr = property.GetCustomAttribute<Header>();
        // 如果特性存在且Name不为空,就收集值
        if (headerAttr != null && !string.IsNullOrEmpty(headerAttr.Name))
        {
            headerNames.Add(headerAttr.Name);
        }
    }

    return headerNames;
}

调用示例

// 创建Person实例
Person person = new Person("first", "last");
// 调用方法获取Header Name列表
List<string> result = GetAttributes(person);
// 输出结果:First Name、Last Name
foreach (var name in result)
{
    Console.WriteLine(name);
}

补充说明

  • GetCustomAttribute<Header>()是C# 6及以上版本的简洁写法,若使用更早版本,可替换为(Header)Attribute.GetCustomAttribute(property, typeof(Header))
  • 方法中加入了obj == null的判断,避免空引用异常
  • 额外判断headerAttr.Name不为空,防止收集无效的空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:31:01