简体   繁体   中英

C# moving auto generated code to better structure code

I am pretty new to C# and wondered if there was a simple way to move the auto-generated code to a separate class file?

For example, if I create a windows form onto which I drag a button. Then if I double click the button it auto generates a click event handler under the main Form1 namespace and class. Is there a way that I can move this code to a separate file (maybe a class.cs file) if I want to structure my code in a neat way rather than having an ever growing main??

All of the quick and dirty 'Hello World' style C# examples just show you how to add items to the form in the way described above... they don't seem to go into best practises on how to structure large code developments where structuring code into separate files can beneficial. Is what am am thinking of necessary or do developers use the standard click handlers (left in the main form) and then use that to call external reference files containing the classes/methods???

I'd be interested if you guys can steer me in the correct direction on the best practices people use to structure large C# form based projects

Many thanks

Michael

Yes, you can move the event handlers to a "separate" class. You already have two files: Form1.cs and Form1.Designer.cs, each of which contain a partial class. At the top of Form1.cs, you will see:

 public partial class Form1 : Form

You can create a new file (called whatever you like) and add in the following:

 public partial class Form1
 {

 }

You can now move any of your event handlers for Form1 into this new file.

All that said, we've got a suite of 4 Winforms applications totalling about 450 controls, and we've never done this. The most buttons we've had on a form where we use the designer to create the event handler is about 10. Once you have a lot of buttons (such as in a menu), you are much better off not using the designer, and creating the items (and their event handlers) by code.

You will also not end up with one form that contains tens of thousands of lines - instead you will create individual controls which contain isolated logic, and then tie these together on the Form.

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