简体   繁体   中英

Method that accept n Number of Parameters in C #

I am Developing an windows Application, oftentimes I need to clear the Textboxes whenever the user save the Record or click on clear button. Currently i am using this code txtboxname.text=string.empty; for each textbox

So can it be possible to write a method that accept the n number of parameter like reading the all the Textboxes in an array and using foreach we can clear them

the main requirement is to write a method which accept the n number of parameter ie The parameter size will be unknown.

If any body having idea about how to do this then please help me. Thanks in Advance.

With the params keyword.

Here is an example:

public void MyMethod(params int[] numbers)
{
   for (int i = 0; i < numbers.Length; i++)
   {
       //numbers[i] is one of the parameters
   }
}

Have a look at params

The params keyword lets you specify a method parameter that takes a variable number of arguments.

您可以使用params ,例如Foo(params Bar[] bars)将接受任意数量的Bar实例作为输入。

You could also pass a collection eg a dictionary or List to your method as a parameter.

Eg

public void DoSomething(List<myCustomObject> lst){
    ...
}

是的,您可以将一个TextBoxes TextBox[]数组作为方法的paremter,然后您可以在方法中迭代它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM