typeof

維基百科,自由的百科全書

typeof程式語言的一種運算符,用於確定變量數據類型。這在程序結構可以接受多種數據類型且無需顯式指出具體類型時非常有用。

在支持類型多態類型轉換的程式語言中,typeof運算符應用於對象時,有2種不同的語義。Visual Basic語言中typeof返回對象的動態類型[1]即返回運行時類型信息而不考慮任何類型轉換。在C#D等語言,[2] or [3]以及C2x中,[4][5]typeof運算符返回操作數的靜態類型。這些語言通常有其他方法可以獲取動態類型信息,如typeid

例子

C語言的GNU擴展語法下,typeof用於定義一些宏:

#define max(a,b) ({ typeof (a) _a = (a); typeof (b) _b = (b); _a > _b ? _a : _b; })

C++中的typeid是由C++標準庫提供,定義於<typeinfo>頭文件,用於判斷某個變量的類型。typeof由編譯器提供(目前僅gcc編譯器支持),用於返回某個變量或表達式的類型。C++11標準新增的decltype是typeof的升級版本。

C#:

// Given an object, returns if it is an integer.
// The "is" operator can be also used to determine this.
public static bool IsInteger(object o) {
  return ( o.GetType() == typeof(int) );
}

VB.NET語言中, C#的"typeof"對應於VB.NET的GetType方法。VB.NET的TypeOf關鍵字用於比較變量引用的對象與一個數據類型兼容。

Dim refInteger As Object = 2

MsgBox("TypeOf Object[Integer] Is Integer? " & TypeOf refInteger Is Integer)
MsgBox("TypeOf Object[Integer] Is Double? " & TypeOf refInteger Is Double)

Dim refForm As Object = New System.Windows.Forms.Form

MsgBox("TypeOf Object[Form] Is Form? " & TypeOf refForm Is System.Windows.Forms.Form)
MsgBox("TypeOf Object[Form] Is Label? " & TypeOf refForm Is System.Windows.Forms.Label)
MsgBox("TypeOf Object[Form] Is Control? " & TypeOf refForm Is System.Windows.Forms.Control)
MsgBox("TypeOf Object[Form] Is IComponent? " & TypeOf refForm Is System.ComponentModel.IComponent)

In JavaScript:

function isNumber(n)
{
  return ( typeof n === 'number' );
}

TypeScript中:[6]

function (param: typeof existingObject) { ... }
let newObject: typeof existingObject;

參見

參考文獻

  1. ^ https://msdn.microsoft.com/en-us/library/0ec5kw18(VS.80).aspx頁面存檔備份,存於互聯網檔案館) "TypeOf Operator (Visual Basic)" in MSDN
  2. ^ https://msdn.microsoft.com/en-us/library/58918ffs(VS.80).aspx頁面存檔備份,存於互聯網檔案館) "typeof (C#)" in MSDN
  3. ^ Declarations - D Programming Language 1.0 - Digital Mars. [2022-03-01]. (原始內容存檔於2022-04-07). 
  4. ^ https://gcc.gnu.org/onlinedocs/gcc/Typeof.html頁面存檔備份,存於互聯網檔案館) "Typeof" in Using the GNU Compiler Collection
  5. ^ Meneide, JeanHeyd. Not-So-Magic - typeof(…) in C | r2. www.open-std.org. 2021-03-07 [2021-12-02]. (原始內容存檔於2021-04-19). 
  6. ^ Using `typeof` to infer a type. Learn TypeScript. [2022-01-28]. (原始內容存檔於2022-04-12) (英語).