我在C#.NET中编程.我想创建一个嵌套类,可以访问创建它的实例的成员,但我似乎无法弄清楚如何.
这就是我想要做的:
Car x = new Car()
x.color = "red";
x.Door frontDoor = new x.Door();
MessageBox.Show(frontDoor.GetColor()); // So I want the method GetColor of the class Front Door to be able to access the color field/property of the Car instance that created it.
我该怎么做?我尝试将Door类嵌套在Car类中,但它无法以这种方式访问Car类的成员.我是否需要让汽车继承门类或其他东西?
解决方法:
最简单的方法是给门类型一个参考回到创建它的汽车.
例如:
class Car {
public string color;
public Door Door() { return new Door(this); }
class Door {
Car owner;
Door(Car owner) { this.owner = owner; }
string GetColor() { return owner.color; }
}
}