如何在 C# 中使用单独的 .cs 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/572314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use separate .cs files in C#?
提问by tejas_grande
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 function would would like to click on a clear button and have it clear all fields on a form. The code is split up into three .cs files. Main.cs, MainForm.Designer.cs and btClear.cs.
论坛; 我是一个新手,正在编写一些代码。我想知道使用包含其他类和函数的单独 .cs 文件的最佳方法。作为一个基本功能的例子,想要点击一个清除按钮并清除表单上的所有字段。代码被分成三个 .cs 文件。Main.cs、MainForm.Designer.cs 和 btClear.cs。
MainForm.Designer.cs contains the designers automatically created code including the Clear Button, and the text boxes I would like to clear.
MainForm.Designer.cs 包含设计者自动创建的代码,包括清除按钮和我想要清除的文本框。
I would like to have the code to clear the text boxes contained in btClear.cs. I understand it would be easy to simply to place this code in MainForm.Designer.cs however I would like to use this as a template in order to use separate .cs files as a standard practice.
我想要清除 btClear.cs 中包含的文本框的代码。我知道简单地将此代码放在 MainForm.Designer.cs 中会很容易,但是我想将其用作模板,以便将单独的 .cs 文件用作标准做法。
Can someone give me an example of how to do this please?
有人可以给我一个如何做到这一点的例子吗?
采纳答案by Sergio Acosta
The way most .net programmers would do it is:
大多数 .net 程序员会这样做:
- Leave all your code inside
MainForm.cs
, but declare a new method for separating the code that does the clearing.
- 将所有代码保留在 中
MainForm.cs
,但声明一个新方法来分隔进行清除的代码。
I always leave in the event handler method (the one VS generates when you double-click the button) code to change the mouse cursor (in case the code I'm calling takes a couple of seconds or more to run) and catch all unhandled exceptions, and put my logic in a separate private method:
我总是保留事件处理程序方法(当您双击按钮时生成的一个 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...
}
}
In my opinion, if you want to follow the conventional way of doing things in .net, you should stick with this first example.
在我看来,如果你想在 .net 中遵循传统的做事方式,你应该坚持第一个例子。
Moving code out of the form .cs files is recommended when the code is not part of the form logic, for example, data access code or business logic. It this case I don't think that clearing the form controls qualifies as business logic. It is just part of the form code and should stay in the MainForm.cs
.
当代码不是表单逻辑的一部分时,例如数据访问代码或业务逻辑,建议将代码移出表单 .cs 文件。在这种情况下,我认为清除表单控件不符合业务逻辑。它只是表单代码的一部分,应该保留在MainForm.cs
.
But if you really want to put the ClearForm
method in another .cs file, you could create a new class and move the ClearForm
method there. You would also need to change the Modifiers property of each control to Public so your new class can have access to them from outside MainForm. Something like this:
但是如果你真的想把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...
}
}
You would have to change the main form code to:
您必须将主表单代码更改为:
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;
}
}
}
But note that your FormCleaner
class would have to know about your MainForm
class in order to know how to clear each of the controls of the form, or you would need to come up with a generic algorithm that is able to loop through the Controls
collection of any form to clean them:
但请注意,您的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 = "";
}
}
}
And as others have said, MainForm.Designer.cs
is machine-generated and you should never put your own code there.
正如其他人所说,它MainForm.Designer.cs
是机器生成的,你永远不应该把自己的代码放在那里。
回答by Chris Ballance
One class per .cs file is a good rule to follow.
每个 .cs 文件一个类是一个很好的规则。
I would not separate page specific functionality into separate .cs files unless you plan to encapsulate into a reusable class.
我不会将特定于页面的功能分离到单独的 .cs 文件中,除非您打算封装到一个可重用的类中。
Edit:
编辑:
Put the clear function in the button's OnClick event. No reason to separate this out.
将清除功能放在按钮的 OnClick 事件中。没有理由把它分开。
.aspx file:
.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 file
.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:
ComplexOperationThingy.cs:
using System;
namespace SimpleWebTest
{
public class ComplexOperationThingy
{
ComplexOperationThingy() { }
public void DoSomethingComplex()
{
//Do your complex operation.
}
}
}
回答by Samuel
You can use a partial
class for your MainForm
class, since that's already being done in MainForm.cs
and MainForm.Designer.cs
.
你可以partial
为你的MainForm
班级使用一个班级,因为这已经在MainForm.cs
和中完成了MainForm.Designer.cs
。
btnClear.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
并在MainForm.cs
或注册该活动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();
如果您想要一种通用的方法,您可以将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();
}
}
回答by Quintin Robinson
It is fairly simple to do. In your btClear.cs file simply generate a class definition like:
做起来相当简单。在您的 btClear.cs 文件中,只需生成一个类定义,如:
public class MyUtility
{
public static void ClearContents(IEnumerable<Control> controls)
{
//TODO: Code that clears contents of controls passed
}
}
Then you can call it from wherever the namespace the generated class is contained in is referenced via:
然后,您可以从包含生成的类的命名空间通过以下方式引用的任何位置调用它:
MyUtility.ClearContents(SomeControlCollection);
I hope I didn't completely miss the mark on your intention.
我希望我没有完全错过你的意图。
回答by Kevin Kibler
I find that it's best to not directly edit the .Designer.cs file, especially from a Source Control standpoint. You can use partial classes to contain you related code; in this case, you can use MainForm.Designer.cs as an example of how to accomplish partial classes (eg. partial class MainForm{}).
我发现最好不要直接编辑 .Designer.cs 文件,尤其是从源代码管理的角度来看。您可以使用分部类来包含相关代码;在这种情况下,您可以使用 MainForm.Designer.cs 作为如何完成分部类(例如分部类 MainForm{})的示例。
If you're adding event handlers through the Windows Forms Designer, it should automatically place them in MainForm.cs, not MainForm.Designer.cs. If you project grows to any significant size, I often find it useful to create multiple partial class files, one for each major group of functionality. This makes it a whole lot easier to find a particular function (and related functions).
如果您通过 Windows 窗体设计器添加事件处理程序,它应该自动将它们放置在 MainForm.cs 中,而不是 MainForm.Designer.cs。如果您的项目增长到任何显着的规模,我经常发现创建多个部分类文件很有用,每个主要功能组一个。这使得查找特定函数(和相关函数)变得更加容易。
回答by Mike Chess
In general you shouldn't put your code in the MainForm.designer.cs file. The *.designer.cs files are used by Visual Studio to wire up all of the tedious plumbing of actually put controls on the form.
通常,您不应将代码放在 MainForm.designer.cs 文件中。*.designer.cs 文件由 Visual Studio 用于连接所有繁琐的实际将控件放置在窗体上的管道。
Any code that you want to use to interact with controls on the form should go MainForm.cs file. So if you want a function to clear controls on the form then you should place the code there.
您想要用于与表单上的控件交互的任何代码都应该放在 MainForm.cs 文件中。所以如果你想要一个函数来清除表单上的控件,那么你应该把代码放在那里。
If you the code that you are writing clear the controls on the form is reusable in other projects then you should put it in another .cs file that can be linked into other projects.
如果您编写的代码明确表单上的控件可在其他项目中重用,那么您应该将其放在另一个可以链接到其他项目的 .cs 文件中。
As Chris said, generally placing one class per .cs file is also a good idea. When you do, the file should have the name of the class it contains. So if you have a class named MyButtonHelpers then the source file should be named MyButtonHelpers.cs.
正如 Chris 所说,通常每个 .cs 文件放置一个类也是一个好主意。当你这样做时,文件应该有它包含的类的名称。因此,如果您有一个名为 MyButtonHelpers 的类,那么源文件应命名为 MyButtonHelpers.cs。
回答by AwesomeTown
The convention in C# (and many other languages) is one file per class (and usually one class per file). There are certainly exceptions to this rule, but splitting a single class across multiple files should be a rare occurrence, not a standard practice.
C#(和许多其他语言)中的约定是每个类一个文件(通常每个文件一个类)。这条规则当然有例外,但是将单个类拆分到多个文件应该很少发生,而不是标准做法。
You mentioned in a comment that you foresee more "complex operations" than the example you gave. What sort of operations are you envisioning? As long as you're just talking about dealing with form controls, the logic belongs in the .cs file for the form (in this case, MainForm.cs, and notMainForm.designer.cs - as others have said, you shouldn't ever modify the .designer file).
您在评论中提到您预见到比您提供的示例更“复杂的操作”。你设想什么样的操作?只要您只是在谈论处理表单控件,逻辑就属于表单的 .cs 文件(在这种情况下,是 MainForm.cs,而不是MainForm.designer.cs - 正如其他人所说,您不应该永远不要修改 .designer 文件)。
If your form is getting too complicated, then it may make sense to break it up into separate custom controls. This would allow you to keep your source files smaller, but (since each Control maps to a class) you'd be adhering to the one class <-> one file convention.
如果您的表单变得过于复杂,那么将其分解为单独的自定义控件可能是有意义的。这将允许您保持源文件更小,但是(因为每个 Control 映射到一个类)您将遵守一个类 <-> 一个文件约定。