How to use separate .cs files in C#?

后端 未结 7 472
没有蜡笔的小新
没有蜡笔的小新 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:45

    One class per .cs file is a good rule to follow.

    I would not separate page specific functionality into separate .cs files unless you plan to encapsulate into a reusable class.

    Edit:

    Put the clear function in the button's OnClick event. No reason to separate this out.

    .aspx file:

    <%@ 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

    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.
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题