项目等级...
class Room
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
public Room()
{
this.Value1 = "one";
this.Value2 = "two";
this.Value3 = "three";
}
}
class Building
{
public Room Room-Bob { get; set; }
public Room Room-Steve{ get; set; }
public Building()
{
this.Room-Bob = new Room();
this.Room-Steve = new Room();
}
}
class Street
{
public Building Building-Black{ get; set; }
public Building Building-Blue { get; set; }
public Building Building-Yellow { get; set; }
public Building Building-White { get; set; }
public Street ()
{
this.Building-Black = new Building();
this.Building-Blue = new Building();
this.Building-Yellow = new Building();
this.Building-White = new Building();
}
}
我目前使用什么来获取值...
class go
{
public void go()
{
string SelectedValue = "";
Street s = new Street();
string PathToProperty = "s.Building1.Room1.value1";
if(PathToProperty == "s.Building1.Room1.value1") { SelectedValue = s.Building1.Room1.Value1; }
if (PathToProperty == "s.Building1.Room1.value2") { SelectedValue = s.Building1.Room1.Value2; }
}
}
我想如何获得这些值...或类似的东西
string PathToProperty = "s.Building1.Room1.value1";
SelectedValue = PathToProperty;
我也想这样设置属性...
string PathToProperty = "s.Building1.Room1.value1";
SelectedValue = PathToProperty;
原因是我通过将一堆组合框中的文本串在一起来制作 PathToProperty。最终,我想避免在组合框中的选项增加时必须添加到我的 IF 语句列表中。
我一直在搞反射,但想避免这种情况,我在某处读到你可以用接口(interface)来做到这一点(使用它们来公开属性),但我不知道如何做。
如果 Reflection 是最好的选择,有人可以告诉我两种获取属性的方法和另一种设置它的方法吗?
最佳答案
我建议您采用不同的方法。 IMO 反射(reflection)不是解决此类情况的方法。
以此为起点,然后以此为基础进行构建——当然,还要重新设计/重构其他部分:
class Room
{
// same as yours
}
class Building
{
public List<Room> Rooms { get; set; }
public Building()
{
Rooms = new List<Room>();
Rooms.Add(new Room());
Rooms.Add(new Room());
// get "room #x" -> var room = objBuilding.Rooms[x];
// get "room #x in building #i" -> var room = objStreet.Buildings[i].Rooms[x];
}
}
class Street
{
public List<Building> Buildings { get; set; }
public Street ()
{
Buildings = new List<Building>();
Buildings.Add(new Building());
Buildings.Add(new Building());
Buildings.Add(new Building());
Buildings.Add(new Building());
// get "building #i" -> var building = objStreet.Buildings[i];
}
}
关于c# - 使用不带反射的字符串获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773246/