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

97 c# attributes

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

例如:

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

Mar*_*ett 172

属性将采用数组.虽然如果你控制属性,你也可以使用params(这对消费者来说更好,IMO):

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

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

[MyCustomAttribute(3, 4, 5)]
class MyClass { }
Run Code Online (Sandbox Code Playgroud)

您的数组创建语法恰好关闭:

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

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

[MyCustomAttribute(new int[] { 3, 4, 5 })]
class MyClass { }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 31

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

[assembly: CLSCompliant(true)]

class Foo : Attribute
{
    public Foo(string[] vals) { }
}
[Foo(new string[] {"abc","def"})]
static void Bar() {}
Run Code Online (Sandbox Code Playgroud)

显示:

Warning 1   Arrays as attribute arguments is not CLS-compliant
Run Code Online (Sandbox Code Playgroud)

对于常规反射使用,可能优选具有多个属性,即

[Foo("abc"), Foo("def")]
Run Code Online (Sandbox Code Playgroud)

但是,这不适用于TypeDescriptor/ PropertyDescriptor,其中只支持任何属性的单个实例(第一个或最后一个获胜,我无法回想起哪个).

  • 注意:多个属性需要属性上的AttributeUsage属性.http://stackoverflow.com/questions/553540/how-to-create-duplicate-allowed-attribute (3认同)

Sco*_*man 22

尝试像这样声明构造函数:

public class MyCustomAttribute : Attribute
{
    public MyCustomAttribute(params int[] t)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用它:

[MyCustomAttribute(3, 4, 5)]


Jon*_*eet 12

那应该没关系.从规范,第17.2节:

如果以下所有语句都为真,则表达式E是attribute-argument-expression:

  • 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
{
}
Run Code Online (Sandbox Code Playgroud)

  • 但请注意CLS合规性 (5认同)

Rob*_*use 5

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

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