问题描述
是否可以在不传递和存储引用的情况下从成员对象访问对象?在下面的示例中,给定的椅子对象是否可以访问房屋对象,而房屋不必将其引用向下传递给成员层次结构?
Is it possible to access an object from a member object without passing and storing a reference? In the example below, could a given chair object get access to the house object without the house having to pass its reference down the members hierarchy?
public class Chair {
public string Material { get; set; }
public Chair() {
Material = "Wood";
}
public bool IsInMiami() {
// Get instance of House where chair is found
House house = ... // Reflection?
return house.City.Equals("Miami");
}
}
public class Room {
private List<Chair> _chairs;
public Room() {
_chairs = new List<Chair>();
_chairs.Add(new Chair());
}
}
public class House {
private List<Room> _rooms;
public string City { get; set; }
public House() {
_rooms = new List<Room>();
_rooms.Add(new Room());
City = "Orlando";
}
}
答案可能是通过反思,但我不知道该怎么做,或者还有另一种方法可以实现这一目标.
The answer could be via reflection but I don't have a clue how to do it, or is there another way to achieve the same.
预先感谢
推荐答案
在没有主席提及众议院的情况下,无法做到这一点.从主席的角度来看,它与众议院之间没有任何关系.实际上,主席可能属于许多议院,也可能不属于任何议院.
There is no way to do that without the Chair having a reference to the House. From the point of view of the Chair, there is no relationship between it and a House. In fact, the Chair could belong to many Houses, or no Houses.
这篇关于获取包含类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!