【发布时间】:2021-04-12 23:14:17
【问题描述】:
我已经创建了构造函数并实例化了我的菜单类并从该类中调用了显示对象。 (下)
public class App
{
//Create field
private User _mainUser;
public App()
{
//Instantiate the menu class
Menu menu = new Menu();
//Call Menu object's Init
menu.Init("Main Menu", "Login", "About", "Exit");
//call Menu objects Display method
menu.Display();
//Instantiate a new user and assign it to _mainUser
_mainUser = new User();
//Call the selection method
Selection();
}
现在,我正在尝试在同一类的另一个方法中使用相同的实例化 menu.Display();。但它希望我再次实例化 Menu 类,然后再次调用 Display 方法。但是当我这样做时,我的菜单显示没有出现。如何在下面显示的另一种方法中使用与构造函数中相同的 menu.Display() 而无需再次实例化它?
private void Continue()
{
//Print out the continue message
Console.Write("Press any key to continue... ");
//Let the user hit a key
Console.ReadLine();
//Clear console
Console.Clear();
//Run menu class Display method
//menu.Display(); <--- What i want to do but I cant
//What its making me do but it won't show my menu because nothing is inside
Menu menu = new Menu();
menu.Display();
//Run selection method
Selection();
}
请帮忙:)
更新**
我得到了我需要的帮助,而且解决方案很简单掌心。
对于其他有同样问题的人;在这些好人的帮助下,我刚刚创建了一个私有的_menu 字段,然后在我的构造函数中声明了它。它工作得很好。代码贴在下面,因为我不擅长解释。
public class App
{
//Create field
private User _mainUser;
//Create a field for the menu class to access it throughout this entire class.
private Menu _menu;
public App()
{
//Instantiate the menu class
_menu = new Menu();
//Call Menu object's Init
_menu.Init("Main Menu", "Login", "About", "Exit");
//call Menu objects Display method
_menu.Display();
//Instantiate a new user and assign it to _mainUser
_mainUser = new User();
//Call the selection method
Selection();
}
【问题讨论】:
-
将菜单创建为实例成员,即一个字段。
private Menu _menu然后你可以在你的类非静态成员的任何地方访问它 -
@00110001 非常感谢!这就像我需要的那样。
标签: c# methods constructor instantiation