[英]How can I make overload simpler
I have a helper class that handles some methods for a toolbar. 我有一个帮助程序类,用于处理工具栏的某些方法。 Now I have created 5 constructor with different overloads. 现在,我创建了5个具有不同重载的构造函数。 My question is, how can I make this contructor overload simpler? 我的问题是,如何使这种构造器过载更简单? The way I am doing it works, but in case I will need to implement fe 10 RichTextBoxes, I don't want to create an overload for every possible RichTextBox and handle everyone in the methods. 我的工作方式有效,但是如果我需要实现10个RichTextBoxes,我不想为每个可能的RichTextBox创建重载并处理方法中的每个人。 I'm convinced there is a simpler way but one way or another, I can see to figure this out. 我相信,有一种更简单的方法,但一种或另一种,我可以看出来。
I tried to make a List but get errors in return that I can't make a list of a namespace which is logic. 我试图创建一个列表,但得到错误,但无法返回逻辑上的命名空间列表。
public class RichtTextBoxHelper
{
private RichTextBox _textBox;
private RichTextBox _textbox2;
private RichTextBox _textbox3;
private RichTextBox _textbox4;
private RichTextBox _textbox5;
public RichtTextBoxHelper(RichTextBox textBox)
{
_textBox = textBox;
}
public RichtTextBoxHelper(RichTextBox textBox, RichTextBox textbox2)
{
_textBox = textBox;
_textbox2 = textbox2;
}
public RichtTextBoxHelper(RichTextBox textBox, RichTextBox textbox2, RichTextBox textbox3)
{
_textBox = textBox;
_textbox2 = textbox2;
_textbox3 = textbox3;
}
public RichtTextBoxHelper(RichTextBox textBox, RichTextBox textbox2, RichTextBox textbox3, RichTextBox textbox4)
{
_textBox = textBox;
_textbox2 = textbox2;
_textbox3 = textbox3;
_textbox4 = textbox4;
}
public RichtTextBoxHelper(RichTextBox textBox, RichTextBox textbox2, RichTextBox textbox3, RichTextBox textbox4, RichTextBox textbox5)
{
_textBox = textBox;
_textbox2 = textbox2;
_textbox3 = textbox3;
_textbox4 = textbox4;
_textbox5 = textbox5;
}
public void CutClick()
{
_textBox.Cut();
_textbox2.Cut();
_textbox3.Cut();
_textbox4.Cut();
_textbox5.Cut();
}
Various methods like the cut one. 各种方法都喜欢切一。
Is there an easier, more clean way to do this? 有没有更简单,更干净的方法来做到这一点?
You should use an array of RichTextBox
s: 您应该使用RichTextBox
的数组:
private RichTextBox[] textBoxes;
Now you only need one constructor: 现在您只需要一个构造函数:
public RichtTextBoxHelper(params RichTextBox[] textBoxes) {
this.textBoxes = textBoxes ?? throw new ArgumentNullException(nameof(textBoxes));
}
If there is a maximum number of text boxes that you can handle, just make a check: 如果您可以处理的文本框数量最多,请检查一下:
public RichtTextBoxHelper(params RichTextBox[] textBoxes) {
if (textBoxes is null)
{
throw new ArgumentNullException(nameof(textBoxes));
}
if (textBoxes.Length > maxTextBoxes) :
throw new ArgumentException("Too many text boxes!", nameof(textBoxes))
}
this.textBoxes = textBoxes;
}
The CutClick
method can be simply: CutClick
方法可以很简单:
public void CutClick() {
foreach(var textBox in textBoxes) {
textBox.Cut();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.