我想将类型数组传递给属性,我尝试这样做
class CustomAttribute: Attribute
{
Type[] included;
Type[] excluded;
}
[CustomAttribute{included = new Type[] {typeof(ComponentA)},
excluded = new Type[] {typeof(ComponentB)} }]//dont work
class Processor
{
// something here
}
但VS显示不能传递属性中的类型。
有人知道如何解决此问题或最终的解决方法吗?
答案 0 :(得分:4)
看起来这与数组无关,而是与你的一般语法有关。您使用{ }
作为属性参数而不是( )
,并且您的属性没有公共属性,属性中的命名参数需要这些属性。此外,您的属性类不使用[AttributeUsage(...)]
。
以下是 编译的完整示例:
using System;
[AttributeUsage(AttributeTargets.All)]
class CustomAttribute : Attribute
{
public Type[] Included { get; set; }
public Type[] Excluded { get; set; }
}
[CustomAttribute(Included = new Type[] { typeof(string) },
Excluded = new Type[] { typeof(int), typeof(bool) })]
class Processor
{
}
让事情更简洁:
new[]
代替new Type[]
所以:
using System;
[AttributeUsage(AttributeTargets.All)]
class CustomAttribute : Attribute
{
public Type[] Included { get; set; }
public Type[] Excluded { get; set; }
// Keep a parameterless constructor to allow for
// named attribute arguments
public CustomAttribute()
{
}
public CustomAttribute(Type[] included, Type[] excluded)
{
Included = included;
Excluded = excluded;
}
}
[CustomAttribute(new[] { typeof(string) }, new[] { typeof(int), typeof(bool) })]
class Processor
{
// Provide the named version still works
[CustomAttribute(Included = new[] { typeof(string) },
Excluded = new[] { typeof(int), typeof(bool) })]
public void Method()
{
}
}
答案 1 :(得分:0)
缺少一些访问修饰符,并且您没有正确使用该属性。
您需要在`CustomAttribute```类中公开included
和exluded
属性:
class CustomAttribute: Attribute
{
public Type[] Included { get; set; }
public Type[] Excluded { get; set; }
}
为属性成员指定值时,需要使用()
而不是{}
你的专栏是:
[CustomAttribute{included = new Type[] {typeof(ComponentA)},excluded = new Type[] {typeof(ComponentB)} }]
应该是:
[CustomAttribute(Included = new Type[] {typeof(ComponentA)}, Excluded = new Type[] {typeof(ComponentB)} )]
请注意(
之后的CustomAttribute
和)
之前的]
。
答案 2 :(得分:0)
您的In [39]: %timeit (dark1(df))
1 loop, best of 3: 15.4 s per loop
In [40]: %timeit (dark2(df))
10 loops, best of 3: 52.7 ms per loop
In [41]: %timeit (jez1(df))
10 loops, best of 3: 38.8 ms per loop
In [42]: %timeit (jez2(df))
10 loops, best of 3: 44.9 ms per loop
字段是私密的。考虑使用公共属性而不是公开字段。 "Why it is preferable to use public properties instead of public fields"
由于您将参数传递给属性的语法不正确,因此您的代码无法编译。你需要:
Type
在将参数(而不是class CustomAttribute: Attribute
{
public Type[] Included { get; set; }
public Type[] Excluded { get; set; }
}
[CustomAttribute(Included = new Type[] {typeof(ComponentA)}, Excluded = new
Type[] {typeof(ComponentB)} )]
class Processor
{
// something here
}
)传递给{}
构造函数时,请注意括号。