【.net core】支持通过属性名称索引的泛型包装类

cs 复制代码
/// <summary>
/// 支持通过属性名称索引的泛型包装类
/// </summary>
public class PropertyIndexer<T> : IEnumerable<T>
{

    private T[] _items;
    private T _instance;
    private PropertyInfo[] _properties;
    private bool _caseSensitive;



    public PropertyIndexer(T item, bool caseSensitive = true)
    {
        _instance = item;
        _caseSensitive = caseSensitive;
        _properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    }

    // 通过属性名称获取值
    public object this[string propertyName]
    {
        get
        {
            PropertyInfo property = FindProperty(propertyName);
            if (property == null)
                throw new ArgumentException($"找不到属性: {propertyName}");

            return property.GetValue(_instance);
        }
        set
        {
            PropertyInfo property = FindProperty(propertyName);
            if (property == null)
                throw new ArgumentException($"找不到属性: {propertyName}");

            // 类型转换
            object convertedValue = Convert.ChangeType(value, property.PropertyType);
            property.SetValue(_instance, convertedValue);
        }
    }

    // 查找属性(支持大小写敏感/不敏感)
    private PropertyInfo FindProperty(string propertyName)
    {
        if (_caseSensitive)
        {
            return Array.Find(_properties, p => p.Name == propertyName);
        }
        else
        {
            return Array.Find(_properties, p => p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));
        }
    }

    // 获取底层实例
    public T Instance => _instance;
    // 实现IEnumerable<T>接口
    public IEnumerator<T> GetEnumerator()
    {
        foreach (T item in _items)
        {
            yield return item;
        }
    }

    // 显式实现非泛型接口
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

实体类转换方法

cs 复制代码
//将实体类集合转换为支持属性名称索引的类
public static List<PropertyIndexer<T>> ConvertToPropertyIndexer<T>(List<T> dataList) {
    List<PropertyIndexer<T>> result = new List<PropertyIndexer<T>>();
    foreach (T item in dataList) {
        result.Add(new PropertyIndexer<T>(item));
    }
    return result;
}
//索引类转换为实体类
public static List<T> ConvertToPropertyIndexer<T>(List<PropertyIndexer<T>> dataList)
{
    List<T> result = new List<T>();
    foreach (PropertyIndexer<T> item in dataList)
    {
        result.Add(item.Instance);
    }
    return result;
}

调用

cs 复制代码
public ClassA{
    public string name {get;set;}
    public string value {get;set;}
}

List<ClassA> list = new List<ClassA>(){
    new ClassA(){name = "a",value="1"  },
    new ClassA(){name = "b",value="2"  },
}

List<PropertyIndexer<ClassA>> values =
   DataCountCenterService.ConvertToPropertyIndexer<ClassA>(list);

Console.WriteLine(values[0]["name"].ToString());//索引取字段值的返回结果是object,需要进行转换,此处输出结果为a
相关推荐
二哈赛车手8 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
为何创造硅基生物8 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好8 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
栗子~~8 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
星寂樱易李8 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
YDS8298 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
仰泳之鹅9 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
之歆9 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
未若君雅裁10 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
cen__y10 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git