Share via


typeid (C++ 元件擴充功能)

取得值,這個值表示物件的型別。

警告

本主題是關於 typeid 的 C++ 元件擴充功能版本。如需此範例的 ISO C++ 版本的關鍵字,請參閱typeid 運算子

所有執行階段

語法

T::typeid

參數

  • T
    型別名稱。

Windows 執行階段

語法

Platform::Type^ type = T::typeid;

參數

  • T
    型別名稱。

備註

在 C++/CX 中,typeid 會傳回從執行階段型別資訊建構的 Platform::Type

需求

編譯器選項:/ZW

Common Language Runtime

語法

type::typeid

參數

  • type
    您要為 System::Type 物件設定之型別 (抽象宣告子) 的名稱。

備註

typeid 在編譯時期用來取得型別的 Type

typeid 類似於使用 GetTypeGetType,在執行階段取得型別的 System::Type。 不過,typeid 只接受型別名稱做為參數。如果您想要型別的執行個體取得其 System::Type 名稱,請使用 GetType。

typeid 必須能夠在編譯時期評估型別名稱 (型別),而 GetType 會評估要在執行階段傳回的型別。

typeid 可以接受原生型別名稱或原生型別名稱的 Common Language Runtime 別名。如需詳細資訊,請參閱C++ 原生類型的 .NET Framework 對應項 (C++/CLI)

typeid 也會使用原生型別,但是仍將傳回 System::Type。若要取得 type_info 結構,請使用 typeid 運算子

typeid 在先前的 /clr 語法中是 __typeof 的後置項。

需求

編譯器選項:/clr

範例

範例

下列範例會將 typeid 關鍵字與 GetType() 成員進行比較。

// keyword__typeid.cpp
// compile with: /clr
using namespace System;

ref struct G {
   int i;
};

int main() {
   G ^ pG = gcnew G;
   Type ^ pType = pG->GetType();
   Type ^ pType2 = G::typeid;

   if (pType == pType2)
      Console::WriteLine("typeid and GetType returned the same System::Type");
   Console::WriteLine(G::typeid);

   typedef float* FloatPtr;
   Console::WriteLine(FloatPtr::typeid);
}

Output

  
  

範例

下列範例顯示,System::Type 型別的變數可以用來取得型別的屬性。這也表示,您必須為某些型別建立 typedef,才能使用 typeid。

// keyword__typeid_2.cpp
// compile with: /clr
using namespace System;
using namespace System::Security;
using namespace System::Security::Permissions;

typedef int ^ handle_to_int;
typedef int * pointer_to_int;

public ref class MyClass {};

class MyClass2 {};

[attribute(AttributeTargets::All)]
ref class AtClass {
public:
   AtClass(Type ^) {
      Console::WriteLine("in AtClass Type ^ constructor");
   }
};

[attribute(AttributeTargets::All)]
ref class AtClass2 {
public:
   AtClass2() {
      Console::WriteLine("in AtClass2 constructor");
   }
};

// Apply the AtClass and AtClass2 attributes to class B
[AtClass(MyClass::typeid), AtClass2]   
[AttributeUsage(AttributeTargets::All)]
ref class B : Attribute {};

int main() {
   Type ^ MyType = B::typeid;

   Console::WriteLine(MyType->IsClass);
   
   array<Object^>^ MyArray = MyType -> GetCustomAttributes(true);
   for (int i = 0 ; i < MyArray->Length ; i++ )
      Console::WriteLine(MyArray[i]);

   if (int::typeid != pointer_to_int::typeid)
      Console::WriteLine("int::typeid != pointer_to_int::typeid, as expected");

   if (int::typeid == handle_to_int::typeid)
      Console::WriteLine("int::typeid == handle_to_int::typeid, as expected");
}

Output

  
  
  
  
  
  
  
  

請參閱

概念

執行階段平台的元件擴充功能