【问题标题】:C# parameter passing List<T>C# 参数传递 List<T>
【发布时间】:2014-08-17 11:31:34
【问题描述】:

我有这个关于 C# 以方法方式清除文本文本框的代码:

public void clearThis(List<TextBox> txtbox){
    foreach (TextBox nTxtbox in txtbox){
        nTxtbox.Text = "";
    }
}

需要帮助,如何传递我的文本框:

clearThis(Arrays.asList(textbox1,textbox2,textbox3)); //something like this method.

这是我的示例代码:

private void btnCancel_Click(object sender, EventArgs e){
    clearThis();
}

【问题讨论】:

    标签: c# parameters


    【解决方案1】:

    你可以使用List&lt;T&gt;构造函数和collection initializer syntax

    clearThis(new List<TextBox>() { textbox1, textbox2, textbox3 });
    

    您也可以将方法更改为采用TextBox[] 数组,并使用params modifier 进行标记:

    public void clearThis(params TextBox[] txtbox){
        foreach (TextBox nTxtbox in txtbox){
            nTxtbox.Text = "";
        }
    }
    

    之后,你就可以这样称呼它了:

    clearThis(textbox1, textbox2, textbox3);
    

    【讨论】:

    • 谢谢朋友,这解决了我的问题,我可以指定要清除的文本框谢谢。
    【解决方案2】:

    首先,我将签名更改为接受IEnumerable&lt;TextBox&gt; 而不是List&lt;TextBox&gt;。您唯一要做的就是枚举参数,因此您需要的唯一功能是可枚举的功能。这将允许您传递任何TextBox 对象序列,而不仅仅是列表。

    其次,我们必须弄清楚您需要哪些文本框。如果你已经知道你想要哪个,那么你可以简单地将它们放入TextBox[](这是一个可枚举的):

    clearThis(new TextBox[] { txtOne, txtTwo, txtThree });
    

    或者,你可以传入一些其他的可枚举,例如:

    clearThis(Controls.OfType<TextBox>());
    

    (请注意,这将进行浅搜索。要执行深度搜索,请考虑使用我为另一个答案编写的this method。然后您可以简单地使用clearThis(GetControlsOfType&lt;TextBox&gt;(this))。)

    【讨论】:

      【解决方案3】:

      如果你想清除表单上的文本框,你可以使用这个方法,

      void ClearAllText(Control formTest)
      {
          foreach (Control c in formTest.Controls)
          {
            if (c is TextBox)
               ((TextBox)c).Clear();
            else
               ClearAllText(c);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-30
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多