How do I write a C# method that takes a variable number of arguments?
Is it possible to send a variable number of arguments to a method?
For instance if I want to write a method that would concatenate many 开发者_如何转开发string[]
objects into one string, but I wanted it to be able to accept arguments without knowing how many I would want to pass in, how would I do this?
You would do this as:
string ConcatString(params string[] arguments)
{
// Do work here
}
This can be called as:
string result = ConcatString("Foo", "Bar", "Baz");
For details, see params (C# Reference).
FYI - There is already a String.Concat(params object[] args)
- it will concatenate any set of objects by calling ToString() on each. So for this specific example, this is probably not really that useful.
You can easily create a method that takes an arbitrary number of arguments (including zero), using the params
keyword:
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
Console.Write(list[i] + " ");
}
You can even pass an array to this method instead of a list of parameters, and the method will work exactly the same.
Use the params
keyword to do that:
public static string ConvertToOneString(params string[] list)
{
string result = String.Empty;
for ( int i = 0 ; i < list.Length ; i++ )
{
result += list[i];
}
return result;
}
Usage:
string s = "hello"
string a = "world"
string result = ConvertToOneString(s, a);
very easy to do so using params keyword
void ConcatString(params String[] strArray)
{
foreach (String s in strArray)
{
// do whatever you want with all the arguments here...
}
}
yes, you can use params for that
Use params
:
void YourMethod(params string[] infiniteArgs) { }
string MyConcat(params string[] values)
{
var s = new StringBuilder();
foreach (var v in values)
s.Append(v);
return s.ToString();
}
You don't mean infinite (the answer to that question is no) but you do mean 'variable'. Here is your answer (yes): http://blogs.msdn.com/b/csharpfaq/archive/2004/08/05/209384.aspx
In practice, infinite - no (there is a finite amount of memory available, for example).
Unknown at design-time, yes.
The classic example of this is how it's handled on a Console application.
http://dotnetperls.com/main
http://msdn.microsoft.com/en-us/library/cb20e19t(VS.71).aspx
精彩评论