通过字符串标识符获取 list<T> 的值

我想通过仅用字符串标识对象来获取 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 作为标识符


猛跑小猪
浏览 117回答 1
1回答

LEATH

从技术上讲,您可以尝试使用Reflection ie按名称查找属性:using System.Reflection;...private static T PropertyReader<T>(object value, string name) {&nbsp; if (null == value)&nbsp; &nbsp; throw new ArgumentNullException(nameof(value));&nbsp; else if (null == name)&nbsp; &nbsp; throw new ArgumentNullException(nameof(name));&nbsp; var prop = value.GetType().GetProperty(name);&nbsp; if (null == prop || !prop.CanRead)&nbsp; &nbsp; throw new ArgumentException($"property {name} has not been found.", nameof(name));&nbsp; return (T)(Convert.ChangeType(prop.GetValue(value, new object[0]), typeof(T)));}然后你可以按如下方式使用它:listobject.Add(PropertyReader<string>(fruit[0], A));
打开App,查看更多内容
随时随地看视频慕课网APP