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

时间:2011-12-23 08:59:59

标签: c# class nested

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

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

Fruit apple = new Fruit();

我想要这样的东西:

apple.eat(); //eats apple
MessageBox.Show(apple.color); //message box showing "red"
MessageBox.Show(apple.physicalProperties.height.ToString()); // message box saying 3

我认为会这样做:

class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    public class physicalProperties{
        public int height = 3;
    }

}

......但是,如果那样,我就不会在这里......

6 个答案:

答案 0 :(得分:3)

如此接近!以下是您的代码应如何阅读:

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();
}

类只定义签名,但嵌套类不会自动成为属性。

作为旁注,我还建议使用.NET的“最佳实践”:

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

如果你这么倾向的话,我相信还有很多关于最佳实践的文档。

答案 1 :(得分:2)

class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    //you have declared the class but you havent used this class
    public class physicalProperties{
        public int height = 3;

    }
    //create a property here of type PhysicalProperties
    public physicalProperties physical;
}

答案 2 :(得分:0)

你可以推断出这个类,然后引用它吗?

class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    public physicalProperties{
        height = 3;
    }

}

public class physicalProperties{
        public int height = 3;
    }

答案 3 :(得分:0)

class Fruit{
    public class physicalProperties{
        public int height = 3;
    }
}

Fruit.physicalProperties确实声明了另一种类型,但是:

  1. 它将是私密的,仅供Fruit成员使用,除非您声明public
  2. 创建类型不会创建该类型的实例,也不会创建Fruit的成员,以允许Fruit的用户访问它。
  3. 您需要添加:

    class Fruit {
      private physicalProperties props;
      public physicalProperties PhysicalProperties { get; private set; }
    

    并在Fruit的{​​默认}构造函数中指定PhysicalProperties physicalProperties的实例。

答案 4 :(得分:0)

您需要公开属性,因为它包含在类physicalProperties的实例中,所以也许您可以这样做

public Fruit()
{
    physical = new physicalProperties();
}

还有一个让它回归的财产

public int Height { get { return physical.height;}}

OR

public physicalProperties physical;

这样你就可以apple.physical.height

答案 5 :(得分:0)

class Fruit{
    public void eat(){
        MessageBox.Show("Fruit eaten");
    }
    public string color = "red";
    public class physicalProperties{
        public int height = 3;
    }
    // create a new instance of the class so its public members
    // can be accessed
    public physicalProperties PhysicalProperties = new physicalProperties();
}

然后您可以像这样访问子属性:

Fruit apple = new Fruit();
MessageBox.Show(apple.PhysicalProperties.height.ToString());