简体   繁体   English

如何使用C#集合初始值设定项调用方法?

[英]How to call a method with the C# collection initializer?

Case 案件

This morning I refactored some Logging method and needed to change a method's 'params' parameter in a normal array. 今天早上,我重构了一些Logging方法,并需要在常规数组中更改方法的“ params”参数。 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? 有什么方法可以在不首先初始化数组的情况下调用Test()

The problem is that C# is trying infer the type of the array. 问题是C#尝试推断数组的类型。 However, you provided values of different types and thus C# cannot infer the type. 但是,您提供了不同类型的值,因此C#无法推断类型。 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. 一旦停止使用params,就没有回头路了。 You will be forced to initialize an array. 您将被迫初始化一个数组。

Alternative continue using params: 或者继续使用参数:

public void Test([CallerMemberName]string callerMemberName = null, params object[] test2){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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