C# List<T> 泛型方法根据字段名取值及Object的取值
/// <summary> /// 泛型List<T>取值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_ListTGetValue_Click(object sender, EventArgs e) { List<ObjectClass> list = new List<ObjectClass>(); list.Add(new ObjectClass { Name = "测试1", Sex = "男" }); list.Add(new ObjectClass { Name = "测试2", Sex = "女" }); var res = GetObj<ObjectClass>(list, "Name"); txt_WordsExtract.Text = res; } /// <summary> /// 泛型方法获取List<T>的值 /// </summary> /// <typeparam name="T">泛型实体类</typeparam> /// <param name="list"></param> /// <param name="code">需查找的字段名称</param> /// <returns></returns> public string GetObj<T>(List<T> list, string code) { string res = string.Empty; foreach (T item in list) { //将对象转为Type在获取属性,最后获取属性值,针对Object类型取值也可以使用这种方式 var codeValue = item.GetType().GetProperty(code).GetValue(item); res += $"{codeValue},"; } return res.TrimEnd(','); } public class ObjectClass { public string Name { get; set; } public string Sex { get; set; } }
结果如下
、
此方法仅个人记录,如果有更好的方法,欢迎指正
本文来自博客园,作者:流纹,转载请注明原文链接:https://www.cnblogs.com/lwk9527/p/17374277.html