gpt4 book ai didi

c# - 如何将对象传递给属性构造函数

转载 作者:IT王子 更新时间:2023-10-29 03:47:29 28 4
gpt4 key购买 nike

我正在尝试将对象传递给属性构造函数,如下所示:

[PropertyValidation(new NullOrEmptyValidatorScheme())]
public string Name { get; private set; }

使用这个属性构造函数:

 public PropertyValidationAttribute(IValidatorScheme validator) {
this._ValidatorScheme = validator;
}

代码无法编译。如何将对象传递给上述属性?

编辑:是的 NullOrEmptyValidatorScheme 实现了 IValidatorScheme。

错误:错误CS0182:属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式。

最佳答案

属性中的值仅限于简单类型;例如,基本常量(包括字符串)和typeof...您不能使用new 或其他更复杂的代码。简而言之;你不能这样做。不过你可以给它类型:

[PropertyValidation(typeof(NullOrEmptyValidatorScheme)]

PropertyValidation 构造函数采用 Type,并在代码中使用 Activator.CreateInstance 来创建对象。请注意,理想情况下,您应该只在内部存储字符串 (AssemblyQualifiedName)。

来自 ECMA 334v4:

§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:

  • 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 Attribute specification

...

An expression E is an attribute-argument-expression if all of the following statements are true:

  • 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.

关于c# - 如何将对象传递给属性构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1235617/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com