我正在寻找一种使用"来访问嵌套公共类的方法。"运营商。 所以对于下面的例子,我想访问嵌套在House类中的Kitchen类。
public class House{
public class Kitchen{
//some public properties
public int numberOfChairs {get; set;}
}
}
//Now want to access Kitchen in another class.
public class Main{
House newHouse = new House();
newHouse.Kitchen.numberOfChairs = 5;
}
any hint and help is much appreciate.
答案 0 :(得分:2)
您需要创建一个Kitchen实例。类似的东西:
House.Kitchen newKitchen = new House.Kitchen();
newKitchen.numberOfChairs = 5;
根据回复更新答案:
在这种情况下,你的House类,也需要有一个Kitchen成员。
public class House{
public class Kitchen{
//some public properties
public int numberOfChairs {get; set;}
}
public House() {
kitchen = new Kitchen();
}
public Kitchen kitchen {get; set;}
}
public class Main{
House newHouse = new House();
newHouse.kitchen.numberOfChairs = 5;
}
答案 1 :(得分:1)
看看这个link。 话虽这么说,你为什么要窝这个班?从您想要使用它的方式以及您已公开的事实来看,为什么不使用Kitchen类型的财产?
答案 2 :(得分:1)
现在,您只声明了一个嵌套类。你的房子里没有那个班级的实例。就个人而言,我认为你甚至不需要一个嵌套的类。这可能是一个普通的课程。但是你需要一个实例:
public class House{
public class Kitchen{
//some public properties
public int numberOfChairs {get; set;}
}
public Kitchen TheKitchen { get; set; }
}
//Now want to access Kitchen in another class.
public class Main{
House newHouse = new House();
newHouse.TheKitchen = new House.Kitchen();
newHouse.TheKitchen.numberOfChairs = 5;
}
答案 3 :(得分:1)
在您的House类中添加Kitchen属性,以便您可以从House访问Kitchen的实例。
public class House{
public Kitchen KitchenProp { get; set; }
public class Kitchen{
//some public properties
public int numberOfChairs {get; set;}
}
}
//Now want to access Kitchen in another class.
public class Main{
House newHouse = new House();
newHouse.KitchenProp = new Kitchen();
newHouse.KitchenProp.numberOfChairs = 5;
}