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

发布于:2025-07-19 ⋅ 阅读:(15) ⋅ 点赞:(0)

/// <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();
    }
}

实体类转换方法

//将实体类集合转换为支持属性名称索引的类
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;
}

调用

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


网站公告

今日签到

点亮在社区的每一天
去签到