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,其中只支持任何属性的单个实例(第一个或最后一个获胜,我无法回想起哪个).
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:
这是一个例子:
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)
是的,但您需要初始化您传入的数组。以下是我们单元测试中行测试的示例,该示例测试可变数量的命令行选项;
[Row( new[] { "-l", "/port:13102", "-lfsw" } )]
public void MyTest( string[] args ) { //... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72730 次 |
| 最近记录: |