c# - 嵌套类?有属性的属性?

mow*_*ker 3 c# nested class

我想创建一个具有子属性的属性的类...

换句话说,如果我做了类似的事情:

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)

......但是,如果那行得通,我就不会在这里......

Sco*_*pey 6

很近!以下是您的代码应该如何阅读:

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 的“最佳实践”:

  • 除非必要,否则不要嵌套类
  • 所有公共成员都应该是属性而不是字段
  • 所有 Public 成员都应该是 PascalCase,而不是 camelCase。

如果您愿意,我相信也有大量关于最佳实践的文档。