如何使用C#集合初始化程序调用方法?

时间:2021-07-22 21:31:56

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.

今天早上我重构了一些Logging方法,需要在普通数组中更改方法的'params'参数。因此,对方法的调用必须使用数组参数进行更改。我希望方法调用尽可能少地改变,因为它是一种使用频繁的实用方法。

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()而不首先初始化数组?

1 个解决方案

#1


4  

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

问题是C#正在尝试推断数组的类型。但是,您提供了不同类型的值,因此C#无法推断出类型。确保所有值都是相同类型,或者在初始化数组时显式声明类型

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.

一旦你停止使用params,就无法回头了。您将*初始化一个数组。

Alternative continue using params:

替代方案继续使用params:

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

#1


4  

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

问题是C#正在尝试推断数组的类型。但是,您提供了不同类型的值,因此C#无法推断出类型。确保所有值都是相同类型,或者在初始化数组时显式声明类型

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.

一旦你停止使用params,就无法回头了。您将*初始化一个数组。

Alternative continue using params:

替代方案继续使用params:

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