简体   繁体   中英

C#.NET 4: How to open a form from inside a class file?

NOTE: I searched and searched for this but I could not find the exact thing I was looking for...

So, I'm making a game that's kinda like Fallout but uses a form GUI instead of an actual first-person game environment. I need the program to load a class file before anything else, and I want that class file to open the main menu. How could I get Main.cs (the class file to load first) to open MainMenu.cs (the form to open)?

This is what I attempted to do last:

Form MainMenu = new MainMenu();
MainMenu.Show();

Doing this brought up these errors:

The type or namespace name 'Form' could not be found (Are you missing a using directive or an assembly reference?) 'System.Windows.Forms.Form.Show(System.Windows.Forms.IWin32Window)' is a 'method' but is used like a 'type'

The first error refers to this line:

Form MainMenu = new MainMenu();

That code doesn't know what Form is. Unless it's in the same namespace (which it really shouldn't be in this case) then you need to either fully qualify it:

System.Windows.Forms.Form mainMenu = new MainMenu();

or add a using directive to the file:

using System.Windows.Forms;

As an additional step, if you haven't already done so, your class library will need an assembly reference to the System.Windows.Forms assembly. (Note that this tightly couples your class library to Windows Forms as a technology. So you won't be able to re-use the code without carrying a reference to Windows Forms.)

If the project itself is fully aware of the types and you're simply missing the using directive, you might more simply use the specific type, even just implicitly:

var mainMenu = new MainMenu();

(Note also how I changed the variable name slightly in some of this code, which leads me to...)


The second error refers to this line:

MainMenu.Show();

MainMenu is a type . And Show is an instance method on an object of said type. This line makes it look like you're calling it as a static method or trying to use Show as a type itself. This is confusing the compiler.

In short, don't give your variables the same exact names as your types. Instead:

Form mainMenu = new MainMenu();
mainMenu.Show();

Your code has some problems, but the breaker is naming an object the same as its class (MainMenu = new MainMenu()). This is confusing the compiler and causing the other errors. The code should read

MainMenu myMainMenu = new MainMenu();
myMainMenu.Show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM