我想创建一个具有子属性的属性的类...
换句话说,如果我做了类似的事情:
Fruit apple = new Fruit();
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
apple.eat(); //eats apple
MessageBox.Show(apple.color); //message box showing "red"
MessageBox.Show(apple.physicalProperties.height.ToString()); // message box saying 3
Run Code Online (Sandbox Code Playgroud)
我认为它会这样做:
class Fruit{
public void eat(){
MessageBox.Show("Fruit eaten");
}
public string color = "red";
public class physicalProperties{
public int height = 3;
}
}
Run Code Online (Sandbox Code Playgroud)
......但是,如果那行得通,我就不会在这里......
很近!以下是您的代码应该如何阅读:
class Fruit{
public void eat(){
MessageBox.Show("Fruit eaten");
}
public string color = "red";
public class PhysicalProperties{
public int height = 3;
}
// Add a field to hold the physicalProperties:
public PhysicalProperties physicalProperties = new PhysicalProperties();
}
Run Code Online (Sandbox Code Playgroud)
一个类只是定义了签名,但嵌套的类不会自动成为属性。
作为旁注,我还建议您遵循 .NET 的“最佳实践”:
如果您愿意,我相信也有大量关于最佳实践的文档。