如何创建一个函数来保存一个代码块,然后执行

本文关键字:一个 代码 然后 执行 保存 何创建 函数 创建 | 更新日期: 2023-09-27 17:55:55

我有两个按钮,它们包含自己的功能(我没有包含在下面的代码片段中,因为它不相关),但它们也包含相同的文本块(显示在下面的代码片段中)。我的问题,因为我是 C# 的初学者,有没有办法让我只编写一次代码并使用我应该调用的函数来代替放置在按钮中?

代码片段:

        private void btnAlpha_Click(object sender, EventArgs e)
        {
//Replace Non Alpha code would go here…
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split(“/n”).Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
        }
private void btnReplace_Click(object sender, EventArgs e)
{
//Replace code would go here…
/*Count number of lines in processed text,
extra line is always counted so -1 brings it to correct number*/
int numLines = copyText.Split(“/n”).Length - 1;
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = copyText.Length - numLines;
//Unprocessed Summary
newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
        }

如何创建一个函数来保存一个代码块,然后执行

在 C# 中,您可以将可重用的代码包含在方法中(如注释中所建议的)。如果代码的某些部分行为不同,则可以将它们封装到单独的方法中。在每个处理程序中重复的代码下方是 MyMethod . btnReplace特定代码在MyReplace中,btnAlpha特定代码在MyAlpha中:

private void btnReplace_Click(object sender, EventArgs e)
{
    MyReplace();
    MyMethod();
}
private void btnAlpha_Click(object sender, EventArgs e)
{
    MyAlpha();
    MyMethod();
}
private void MyReplace()
{
    // Replace code
}
private void MyAlpha()
{
    // Alfa code
}
private void MyMethod()
{
    //Replace code would go here…
    /*Count number of lines in processed text,
    extra line is always counted so -1 brings it to correct number*/
    int numLines = copyText.Split(“/n”).Length - 1;
    //seperate certain characters in order to find words
    char[] seperator = (" " + nl).ToCharArray();
    //number of words, characters and include extra line breaks variable
    int numberOfWords = copyText.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
    int numberOfChar = copyText.Length - numLines;
    //Unprocessed Summary
    newSummary = nl + "Word Count: " + numberOfWords + nl + "Characters Count: " + numberOfChar;
}

如果您需要方法之间的某种通信,那么一种选择是从第一个方法返回一个值并将其传递到第二个方法中。

或者,您可以参数化您的 main 方法(如果为 true,则执行 alfa part 否则执行替换部分),并使用一个参数执行它,说明要执行代码的哪一部分。但是,如果有许多可能的替代方案,那么为每个替代方案生产单独的方法可能更有意义。