特性参数类型(C++/CLI 和 C++/CX)

编译器在编译时必须知道传递给特性的值。 特性参数可为下列类型:

  • bool

  • charunsigned char

  • shortunsigned short

  • intunsigned int

  • longunsigned long

  • __int64unsigned __int64

  • floatdouble

  • wchar_t

  • char*wchar_t*System::String*

  • System::Type ^

  • System::Object ^

  • enum

示例:特性参数类型

代码

// attribute_parameter_types.cpp
// compile with: /clr /c
using namespace System;
ref struct AStruct {};

[AttributeUsage(AttributeTargets::ReturnValue)]
ref struct Attr : public Attribute {
   Attr(AStruct ^ i){}
   Attr(bool i){}
   Attr(){}
};

ref struct MyStruct {
   static AStruct ^ x = gcnew AStruct;
   [returnvalue:Attr(x)] int Test() { return 0; }   // C3104
   [returnvalue:Attr] int Test2() { return 0; }   // OK
   [returnvalue:Attr(true)] int Test3() { return 0; }   // OK
};

示例:未命名参数在命名参数之前

说明

当指定特性时,所有未命名(位置)的自变量必须优先于命名自变量。

代码

// extending_metadata_c.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Class)]
ref class MyAttr : public Attribute {
public:
   MyAttr() {}
   MyAttr(int i) {}
   property int Priority;
   property int Version;
};

[MyAttr]
ref class ClassA {};   // No arguments

[MyAttr(Priority = 1)]
ref class ClassB {};   // Named argument

[MyAttr(123)]
ref class ClassC {};   // Positional argument

[MyAttr(123, Version = 1)]
ref class ClassD {};   // Positional and named

示例:一维数组特性参数

说明

特性参数可以为上述类型的一维数组。

代码

// extending_metadata_d.cpp
// compile with: /clr /c
using namespace System;

[AttributeUsage(AttributeTargets::Class)]
public ref struct ABC : public Attribute {
   ABC(array<int>^){}
   array<double> ^ param;
};

[ABC( gcnew array<int> {1,2,3}, param = gcnew array<double>{2.71, 3.14})]
ref struct AStruct{};

另请参阅

用户定义的属性