我可以用数组或其他可变数量的参数初始化C#属性吗?

我可以用数组或其他可变数量的参数初始化C#属性吗?,c#,attributes,C#,Attributes,是否可以创建一个可以用可变数量的参数初始化的属性 例如: [MyCustomAttribute(new int[3,4,5])] // this doesn't work public MyClass ... 可以,但需要初始化要传入的数组。下面是我们单元测试中的一个行测试示例,该测试测试了数量可变的命令行选项 [Row( new[] { "-l", "/port:13102", "-lfsw" } )] public void MyTest( string[] args ) { //...

是否可以创建一个可以用可变数量的参数初始化的属性

例如:

[MyCustomAttribute(new int[3,4,5])]  // this doesn't work
public MyClass ...

可以,但需要初始化要传入的数组。下面是我们单元测试中的一个行测试示例,该测试测试了数量可变的命令行选项

[Row( new[] { "-l", "/port:13102", "-lfsw" } )]
public void MyTest( string[] args ) { //... }

那应该没问题。根据规范第17.2节:

如果以下所有语句均为真,则表达式E为属性参数表达式:

  • E的类型为属性参数类型(§17.1.3)
  • 在编译时,E的值可以解析为以下值之一:
    • 常数值
    • 一个System.Type对象
    • 属性参数表达式的一维数组
下面是一个例子:

using System;

[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class SampleAttribute : Attribute
{
    public SampleAttribute(int[] foo)
    {
    }
}

[Sample(new int[]{1, 3, 5})]
class Test
{
}

尝试按如下方式声明构造函数:

public class MyCustomAttribute : Attribute
{
    public MyCustomAttribute(params int[] t)
    {
    }
}
然后你可以像这样使用它:


[MyCustomAttribute(3,4,5)]
您可以这样做。另一个例子是:

class MyAttribute: Attribute
{
    public MyAttribute(params object[] args)
    {
    }
}

[MyAttribute("hello", 2, 3.14f)]
class Program
{
    static void Main(string[] args)
    {
    }
}

属性将采用数组。虽然如果控制属性,也可以使用
params
(这对消费者更有利,IMO):

您创建数组的语法恰好处于禁用状态:

class MyCustomAttribute : Attribute {
    public int[] Values { get; set; }

    public MyCustomAttribute(int[] values) {
        this.Values = values;
    }
}

[MyCustomAttribute(new int[] { 3, 4, 5 })]
class MyClass { }

您可以这样做,但它不符合CLS:

[assembly: CLSCompliant(true)]

class Foo : Attribute
{
    public Foo(string[] vals) { }
}
[Foo(new string[] {"abc","def"})]
static void Bar() {}
显示:

Warning 1   Arrays as attribute arguments is not CLS-compliant
对于常规反射用法,最好具有多个属性,即

[Foo("abc"), Foo("def")]

但是,这对
TypeDescriptor
/
PropertyDescriptor
不起作用,因为它只支持任何属性的一个实例(无论是第一个还是最后一个,我想不起来是哪个),可以使用数组参数定义属性,但使用数组参数应用属性不符合CLS。但是,仅定义具有数组属性的属性是完全符合CLS的


让我意识到这一点的是,Json.NET是一个符合CLS的库,它有一个属性类JsonPropertyAttribute,该属性名为ItemConverterParameters,它是一个对象数组。

你只是把数组的语法搞错了。它应该是“newint[]{3,4,5}”。注意CLS遵从性,注意:多个属性需要在属性上使用AttributeUsage属性。
[Foo("abc"), Foo("def")]