属性のパラメーターの型 (C++/CLI および C++/CX)

コンパイル時に、属性に渡される値をコンパイラに通知する必要があります。 属性のパラメーターには、次のいずれかの型を指定できます。

  • bool

  • $

  • $

  • $

  • $

  • __int64, unsigned __int64

  • $

  • 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

例: 1 次元配列の属性パラメーター

説明

属性のパラメーターには、前述の型の 1 次元の配列を指定できます。

コード

// 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{};

関連項目

ユーザー定義の属性