我想创建一个具有子属性的属性的类......
换句话说,如果我做了类似的事情:
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;
}
}
......但是,如果那样,我就不会在这里......
答案 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的“最佳实践”:
如果你这么倾向的话,我相信还有很多关于最佳实践的文档。
答案 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
确实声明了另一种类型,但是:
Fruit
成员使用,除非您声明public
。Fruit
的成员,以允许Fruit
的用户访问它。您需要添加:
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());