仅传递字符串数组时,为什么编译器会因为非常量表达式而报错

Bla*_*iar 5 c# nunit visual-studio-2013

当我将字符串数组传递给这样的测试函数时:

[TestCase( new string[] { "1", "2", "3" }, 1 )]
[TestCase( new string[] { "54", "508" }, 1 )]
[TestCase( new string[] { "768" }, 2 )]
public void someTest( string[] someStrings, int someNumber ) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

编译工作正常。

但是,如果我删除整数参数,如以下代码片段所示:

[TestCase( new string[] { "1", "2", "3" } )]
[TestCase( new string[] { "54", "508" } )]
[TestCase( new string[] { "768" } )]
public void someTest( string[] someStrings ) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

出现消息的编译器错误An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

我基本上得到了错误的原因,即数组不是常量类型。但是为什么编译器会接受一个数组,如果有另一个参数传递给测试函数呢?如果我在 TestCase 中放入另一个数组,它甚至可以工作:

[TestCase( new string[] { "1", "2", "3" }, new int[] { 1, 2, 3 } )]
[TestCase( new string[] { "54", "508" }, new int[] { 54, 508 } )]
[TestCase( new string[] { "768" }, new int[] { 768 } )]
public void someTest( string[] someStrings, int[] someNumbers ) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 3

让我们将其简化为不涉及重载的情况,并删除params

using System;

[AttributeUsage(AttributeTargets.All)]
class FooAttribute : Attribute
{
    public FooAttribute(object[] args)
    {
    }
}

// Error
[Foo(new string[] { "a", "b" })]
class FooTest1 {}

// Error
[Foo(new[] { "a", "b" })]
class FooTest2 {}

// Error
[Foo(args: new string[] { "a", "b" })]
class FooTest3 {}

// Error
[Foo((object[]) new string[] { "a", "b" })]
class FooTest4 {}

// Works
[Foo(new object[] { "a", "b" })]
class FooTest5 {}

// Works
[Foo(new[] { (object) "a", "b" })]
class FooTest6 {}
Run Code Online (Sandbox Code Playgroud)

基本上编译器不愿意string[]为 a 提供 aobject[]属性中的参数提供 a ,尽管这通常没问题。

在检查了规范后,我相信这是一个编译器错误 - 但我不想肯定地说。该表达式new string[] { "a", "b" }确实算作规范术语中的属性参数表达式- 如果您将参数类型更改为string[]它,它就可以正常工作。因此,问题在于该参数类型对参数的应用。该规范还表示属性参数和实参“受到与简单赋值相同的规则的约束” - 但在这种情况下这很好。所以我在规范中看不到任何禁止这样做的内容。