我有两个按钮,它们包含自己的功能(我没有在下面的代码片段中包含它,因为它不相关),但它们也包含相同的文本块(显示在下面的代码片段中)。我的问题是因为我是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;
}
答案 0 :(得分:1)
在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 else执行replace part)并使用参数来执行它,该参数说明要执行的代码部分。但是,如果有许多可能的替代方案,那么可能为每种方案制作单独的方法更有意义。