如何将对象传递到属性构造 [英] How to pass objects into an attribute constructor
问题描述
我试图传递对象到属性构造如下:
I am attempting to pass objects into an Attributes constructor as follows:
[PropertyValidation(new NullOrEmptyValidatorScheme())]
public string Name { get; private set; }
使用这个属性的构造函数:
With this attribute constructor:
public PropertyValidationAttribute(IValidatorScheme validator) {
this._ValidatorScheme = validator;
}
在code将无法编译。我怎么能传递一个对象到一个属性如上面?
The code won't compile. How can I pass an object into an attribute as above?
编辑:是NullOrEmptyValidatorScheme实现IValidatorScheme。
Yes NullOrEmptyValidatorScheme implements IValidatorScheme.
错误:错误CS0182:属性参数必须是一个常量前pression,属性参数类型的typeof前pression或数组创建前pression
The error: error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.
推荐答案
为属性的值限于简单类型;例如,基本常数(包括字符串)和的typeof
...你不能使用新
或其它更复杂code。简而言之;你不能做到这一点。你可以给它在类型虽然
The values into attributes are limited to simple types; for example, basic constants (including strings) and typeof
... you can't use new
or other more complex code. In short; you can't do this. You can give it the type though:
[PropertyValidation(typeof(NullOrEmptyValidatorScheme)]
即。在 PropertyValidation
构造函数需要键入
,并使用 Activator.CreateInstance
在code创建的对象中。请注意,您应该理想只是内部存储的字符串( AssemblyQualifiedName
)。
i.e. the PropertyValidation
ctor takes a Type
, and use Activator.CreateInstance
inside the code to create the object. Note that you should ideally just store the string internally (AssemblyQualifiedName
).
从ECMA 334v4:
From ECMA 334v4:
§24.1.3属性参数类型
§24.1.3 Attribute parameter types
类型的位置并命名
一个属性类的参数
仅限于的属性参数
类型的,它们是:
The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
- 一个以下几类:
布尔
,字节
,字符
双击
,浮动
,INT
,长
,短
,字符串
。 - 类型
对象
。 - 类型
的System.Type
。 - 枚举类型,只要它具有公共可达性和
在它被嵌套(如有的话)类型的
也有公众可访问性。 - 上面的一维数组
类型。
- One of the following types:
bool
,byte
,char
,double
,float
,int
,long
,short
,string
. - The type
object
. - The type
System.Type
. - An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
- Single-dimensional arrays of the above types.
和
§24.2属性规范
...
这是前pression 电子
是一个
属性参数前pression如果所有
下面的语句是正确的:
An expression E
is an
attribute-argument-expression if all
of the following statements are true:
- 类型
电子
是一个属性
参数类型(§24.1.3)。 - 在编译时,E的值可以是
解析为以下之一:
- 一个恒定值。
- 系统的typeof-EX pression(§14.5.11)指定非通用
类型,一个封闭的构造类型
(§25.5.2),或绑定的泛型类型
(§25.5)。 - A的一维数组
属性参数前pressions。
- The type of
E
is an attribute parameter type (§24.1.3). - At compile-time, the value of E can be
resolved to one of the following:
- A constant value.
- A typeof-expression (§14.5.11) specifying a non-generic type, a closed constructed type (§25.5.2), or an unbound generic type (§25.5).
- A one-dimensional array of attribute-argument-expressions.
这篇关于如何将对象传递到属性构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!