考虑下面的代码为什么对象是孤儿,当创作者存在
public class City
{
public string Name { get { return "New York"; } }
Building empEstate;
Building nyTimes;
public void Init()
{
// I hate passing "this" to all object
empEstate = new EmpEstate(this);
setSomeProperty(empEstate);
// any one can create new object of some other city
// and pass to the building
nyTimes = new NYTimes(this);
...
other = new OtherBuildings(this)
}
public void PrintAddresses()
{
empEstate.Print();
nyTimes.Print();
...
other.Print();
}
}
public abstract class Building {
City _city;
public Building(City city){
this._city = city;
}
public abstract string Name { get;}
public void Print(){
Console.WriteLine(this.Name);
Console.Write(",");
Console.WriteLine(this._city.Name);
}
}
我想更好的解决方案,以这种方法的第一件事。打印只是一个例子。其实每个建筑物都会向City物件提出一些事件。我不想为每座建筑物添加处理程序,因为城市中可能有几座建筑物。此外,我不想将它们中的每一个都添加到列表中,因为它是每个建筑的两个任务(一个初始化和第二个添加到列表中,一个在编写新建筑时忘记添加到列表中)。为此,我希望调用者自动可用于被调用者,如控件的父属性(尽管它已添加到this.Controls中)
使用内存,我们可以知道当前对象的父代是谁。 GC如何知道该对象未被引用(包括创建者)。我们不能使用内存创建一个方法(安全或不安全)来识别调用者对象。我看到我们可以使用StackTrace来查看调用hirarchy,我们可以在创建新对象时在这里拦截。
你甚至认为'父'是什么? – CodesInChaos
父母可以说对象被声明或创建的对象。 – hungryMind