热门问题
时间线
聊天
视角
typeof
来自维基百科,自由的百科全书
Remove ads
typeof是程式語言的一種運算符,用於確定變量的數據類型。這在程序結構可以接受多種數據類型且無需顯式指出具體類型時非常有用。
![]() | 此條目包含過多行話或專業術語,可能需要簡化或提出進一步解釋。 (2022年3月1日) |
在支持類型多態和類型轉換的程式語言中,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' );
}
function (param: typeof existingObject) { ... }
let newObject: typeof existingObject;
Remove ads
參見
參考文獻
Wikiwand - on
Seamless Wikipedia browsing. On steroids.
Remove ads