How to use separate .cs files in C#?

后端 未结 7 487
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 00:55

Forum; I am a newbie working out a bit of code. I would like to know the best way to use separate .cs files containing other classes and functions. As an example of a basic func

7条回答
  •  广开言路
    2021-02-02 01:27

    You can use a partial class for your MainForm class, since that's already being done in MainForm.cs and MainForm.Designer.cs.

    btnClear.cs

    public partial class MainForm
    {
       private void clearForm(object sender, EventArgs e)
       {
         // ...
       }
    }
    

    And register for the event in MainForm.cs or MainForm.Designer.cs

    this.btnClear.click += clearForm;
    

    Edit:

    If you want a generic way of doing it, you could set the Tag property of your controls to be the default value. And with an extension method, you could do something like formGroup.Reset();

    using System.Windows.Forms;
    
    public class ControlExtensions
    {
      public void Reset(this Control control)
      {
        if (control.Tag != null)
        {
          if (control is TextBoxBase && control.Tag is string)
          {
            control.Text = control.Tag as string;
          }
          else if (control is CheckBox && control.Tag is bool)
          {
            control.Checked = control.Tag as bool;
          }
          // etc
        }
    
        foreach (Control child in control.Children)
          child.Reset();
      }
    }
    

提交回复
热议问题