簡體   English   中英

如何在C#中使用單獨的.cs文件?

[英]How to use separate .cs files in C#?

論壇; 我是一個新手,編寫了一些代碼。 我想知道使用包含其他類和函數的單獨.cs文件的最佳方法。 作為基本功能的一個示例,您可以單擊清除按鈕並清除表單上的所有字段。 代碼分為三個.cs文件。 Main.cs,MainForm.Designer.cs和btClear.cs。

MainForm.Designer.cs包含設計者自動創建的代碼,包括Clear Button和我想要清除的文本框。

我想讓代碼清除btClear.cs中包含的文本框。 我理解簡單地將此代碼放在MainForm.Designer.cs中會很容易,但我想將其用作模板,以便使用單獨的.cs文件作為標准做法。

有人可以給我一個如何做到這一點的例子嗎?

大多數.net程序員都會這樣做:

  • 將所有代碼保留在MainForm.cs ,但聲明一種新方法來分隔執行清除的代碼。

我總是留在事件處理程序方法(雙擊按鈕時生成VS)代碼更改鼠標光標(如果我調用的代碼需要幾秒或更長時間才能運行)並捕獲所有未處理的異常,並將我的邏輯放在一個單獨的私有方法中:

partial class MainForm : Form // this is MainForm.cs
{
    // This is the method VS generates when you double-click the button
    private void clearButton_Click(object sender, EventArgs e)
    {
        this.Cursor = Cursors.WaitCursor;
        try
        {
            ClearForm();
        }
        catch(Exception ex)
        {
            // ... have here code to log the exception to a file 
            // and/or showing a message box to the user
        }
        finally
        {
            this.Cursor = Cursors.Default;
        }
    }

    private void ClearForm()
    {
        // clear all your controls here
        myTextBox.Clear();
        myComboBox.SelectedIndex = 0;
        // etc...
    }
}

在我看來,如果你想在.net中遵循傳統的做事方式,你應該堅持第一個例子。

當代碼不是表單邏輯的一部分時,建議將代碼移出表單.cs文件,例如,數據訪問代碼或業務邏輯。 在這種情況下,我認為清除表單控件不符合業務邏輯。 它只是表單代碼的一部分,應該保留在MainForm.cs

但是如果你真的想將ClearForm方法放在另一個.cs文件中,你可以創建一個新類並在那里移動ClearForm方法。 您還需要將每個控件的Modifiers屬性更改為Public,以便新類可以從MainForm外部訪問它們。 像這樣的東西:

public class FormCleaner // this is FormCleaner.cs
{
    public void ClearForm(MainForm form)
    {
        // clear all your controls here
        form.myTextBox.Clear();
        form.myComboBox.SelectedIndex = 0;
        // etc...
    }
}

您必須將主表單代碼更改為:

partial class MainForm : Form // this is MainForm.cs
{
    // This is the method VS generates when you double-click the button
    private void clearButton_Click(object sender, EventArgs e)
    {
        this.Cursor = Cursors.WaitCursor;
        try
        {
            FormCleaner cleaner = new FormCleaner();
            cleaner.ClearForm(this);
        }
        catch(Exception ex)
        {
            // ... have here code to log the exception to a file 
            // and/or showing a message box to the user
        }
        finally
        {
            this.Cursor = Cursors.Default;
        }
    }
}

但請注意,您的FormCleaner類必須知道您的MainForm類才能知道如何清除表單的每個控件,或者您需要提出一個能夠遍歷Controls集合的通用算法。任何清潔它們的形式:

public class FormCleaner // this is FormCleaner.cs
{
    // 'generic' form cleaner
    public void ClearForm(Form form)
    {
        foreach(Control control on form.Controls)
        {
            // this will probably not work ok, because also
            // static controls like Labels will have their text removed.
            control.Text = "";
        }
    }
}

正如其他人所說, MainForm.Designer.cs是機器生成的,你永遠不應該把自己的代碼放在那里。

您可以為MainForm類使用partial類,因為它已經在MainForm.csMainForm.Designer.cs

btnClear.cs

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

並在MainForm.csMainForm.Designer.cs注冊該事件

this.btnClear.click += clearForm;

編輯:

如果您想要一種通用的方法,可以將控件的Tag屬性設置為默認值。 使用擴展方法,您可以執行類似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();
  }
}

每個.cs文件一個類是一個很好的規則。

除非您打算封裝到可重用的類中,否則我不會將頁面特定的功能分成單獨的.cs文件。

編輯:

將clear函數放在按鈕的OnClick事件中。 沒理由把它分開。

.aspx文件:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SimpleWebTest._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="ClearButton" runat=server onclick="ClearButton_Click" Text="Button" />
    </div>
    </form>
</body>
</html>

.cs文件

using System;

namespace SimpleWebTest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) { }

        protected void ClearButton_Click(object sender, EventArgs e)
        {
            using (ComplexOperationThingy cot = new ComplexOperationThingy())
            {
                cot.DoSomethingComplex();
            }
        }
    }
}

ComplexOperationThingy.cs:

using System;

namespace SimpleWebTest
{
    public class ComplexOperationThingy
    {
        ComplexOperationThingy() { }

        public void DoSomethingComplex()
        {
            //Do your complex operation.
        }
    }
}

這很簡單。 在你的btClear.cs文件中,只需生成一個類定義,如:

public class MyUtility
{
    public static void ClearContents(IEnumerable<Control> controls)
    {
        //TODO: Code that clears contents of controls passed
    }
}

然后,您可以通過以下方式從包含生成的類的命名空間的任何位置調用它:

MyUtility.ClearContents(SomeControlCollection);

我希望我沒有完全錯過你的意圖。

通常,您不應將代碼放在MainForm.designer.cs文件中。 Visual Studio使用* .designer.cs文件連接表單上實際放置控件的所有繁瑣管道。

您要用於與表單上的控件交互的任何代碼都應該是MainForm.cs文件。 因此,如果您希望函數清除表單上的控件,那么您應該將代碼放在那里。

如果您正在編寫的代碼清除表單上的控件可以在其他項目中重用,那么您應該將它放在另一個可以鏈接到其他項目的.cs文件中。

正如克里斯所說,通常每個.cs文件放一個類也是個好主意。 執行此操作時,該文件應具有其包含的類的名稱。 因此,如果您有一個名為MyButtonHelpers的類,則源文件應命名為MyButtonHelpers.cs。

我發現最好不要直接編輯.Designer.cs文件,特別是從源代碼管理的角度來看。 您可以使用部分類來包含相關代碼; 在這種情況下,您可以使用MainForm.Designer.cs作為如何完成部分類的示例(例如,部分類MainForm {})。

如果要通過Windows窗體設計器添加事件處理程序,它應自動將它們放在MainForm.cs中,而不是MainForm.Designer.cs中。 如果項目增長到任何顯着大小,我經常會發現創建多個部分類文件很有用,每個主要功能組都有一個。 這使得查找特定函數(和相關函數)變得更加容易。

C#(和許多其他語言)中的約定是每個類一個文件(通常每個文件一個類)。 這個規則當然有例外,但是在多個文件中拆分單個類應該是罕見的,而不是標准做法。

您在評論中提到,您可以預見到比您給出的示例更“復雜的操作”。 你想要什么樣的行動? 只要你剛剛討論處理表單控件,邏輯就屬於.cs文件中的表單(在本例中,MainForm.cs,而不是 MainForm.designer.cs - 正如其他人所說,你不應該'永遠修改.designer文件)。

如果您的表單過於復雜,那么將其分解為單獨的自定義控件可能是有意義的。 這將允許您保持較小的源文件,但(因為每個Control映射到一個類)您將遵守一個類< - >一個文件約定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM