我在 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 类的成员。我需要让 Car 继承门类吗?
最佳答案
最简单的方法是给 Door
类型一个对创建它的 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; }
}
}
关于c# - 你如何创建一个可以访问创建它的类的成员的嵌套类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2292731/