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) (英语).