我有一个对象列表,其中每个对象都有特定的颜色。 该列表也是在唯一变量下定义的,
List<obj> listofobjs = new List<obj>();
我想做的是从一个字符串开始,例如:
"listofobjs[2].Color"
识别对象列表,以及其中对象 2 的颜色。
到目前为止,我可以通过以下方式返回列表:
string startpoint = "listofobjs[2].Color";
List<obj> test = (List<obj>)this.GetType().GetField(startpoint.Split('[')[0]).GetValue(this);
但是通过测试,我无法从字符串中分配 [2] 和颜色。 我可以用
MessageBox.Show(test[2].Color);
但是,任何人都知道这并不实际。我如何从字符串中返回列表索引 2 以及我们在那里的属性 Color?
感谢您的帮助
我尝试在控制台应用程序中检索您的需求,但似乎
GetProperty
有效,而不是 GetFied
public class obj
{
public string color { get; set; }
}
测试.cs
public class Test
{
public static List<obj> listofobjs { get; set; } = new List<obj>()
{
new obj(){color="red"},
new obj(){color="blue"},
new obj(){color="white"},
new obj(){color="black"},
};
public void showColor(string startpoint)
{
var name = startpoint.Split('[')[0];
var index =Int32.Parse( startpoint.Split('[')[1].Split(']')[0]);
List<obj> test = (List<obj>)this.GetType().GetProperty (name).GetValue(this);
Console.WriteLine(test[index].color);
}
}