问题
Case
This morning I refactored some Logging method and needed to change a method's 'params' parameter in a normal array. Consequently, the call to the method had to change with an array parameter. I'd like the method call to change as less as possible, since it's a heavily used utility method.
I assumed I should be able to use the collection initializer to call the method, but it gave me a compile-error. See the second call in the example below. The third call would be fine too, but also results in an error.
Example
void Main()
{
// This works.
object[] t1 = { 1, "A", 2d };
Test(t1);
// This does not work. Syntax error: Invalid expression term '{'.
Test({1, "A", 2d });
// This does not work. Syntax error: No best type found for implicitly-typed array.
Test(new[] { 1, "A", 2d });
// This works.
Test(new object[] { 1, "A", 2d });
}
void Test(object[] test)
{
Console.WriteLine(test);
}
Question
- Is there any way to call
Test()
without initializing an array first?
回答1:
The problem is that C# is trying infer the type of the array. However, you provided values of different types and thus C# cannot infer the type. Either ensures that all you values are of the same type, or explicitly state the type when you initialize the array
var first = new []{"string", "string2", "string3"};
var second = new object[]{0.0, 0, "string"};
Once you stop using params there is no way back. You will be forced to initialize an array.
Alternative continue using params:
public void Test([CallerMemberName]string callerMemberName = null, params object[] test2){}
来源:https://stackoverflow.com/questions/22605955/how-to-call-a-method-with-the-c-sharp-collection-initializer