我想通过仅用字符串标识对象来获取 List 中项目的值string A ="some_string"; listobject.Add(fruit[0].A);public class apple { public string labbnummer { get; set; } public string red { get; set; } public string gren { get; set; } public string blue { get; set; } public string purple { get; set; }}public List<apple> fruit = new List<apple>();public List<apple> rutten_fruit = new List<apple>();List<string> myfruitlist = new List<string>();myfruitlist.Add("green"); myfruitlist.Add("red"); public void populate{ while (reader.Read()) { apple tasty = new apple(); tasty.green = (string)reader["green"]; tasty.red = (string)reader["red"]; if (list_nr == 0) { fruit.Add(tasty); }}public void orange(){ foreach (var items in myfruitlist) { var A =items; rutten_fruit.Add(fruit[0].A.ToString()); }}它不接受 listobject.Add(fruit[0].A); A 作为标识符
1 回答
LEATH
TA贡献1936条经验 获得超6个赞
从技术上讲,您可以尝试使用Reflection ie按名称查找属性:
using System.Reflection;
...
private static T PropertyReader<T>(object value, string name) {
if (null == value)
throw new ArgumentNullException(nameof(value));
else if (null == name)
throw new ArgumentNullException(nameof(name));
var prop = value.GetType().GetProperty(name);
if (null == prop || !prop.CanRead)
throw new ArgumentException($"property {name} has not been found.", nameof(name));
return (T)(Convert.ChangeType(prop.GetValue(value, new object[0]), typeof(T)));
}
然后你可以按如下方式使用它:
listobject.Add(PropertyReader<string>(fruit[0], A));
- 1 回答
- 0 关注
- 116 浏览
添加回答
举报
0/150
提交
取消