類
/// <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