typeof是一个运算符关键字,用于在编译时获取类型。换句话说,此运算符用于获取类型的System.Type
对象。该运算符将Type本身作为参数,并返回标记的参数类型。
要点:
- typeof运算符的操作数始终是参数的类型或类型的名称。它不包含变量。
- 不允许重载typeof运算符。
- 允许在开放的泛型类型上使用typeof运算符。
- 允许对有界或无界类型使用typeof运算符。
句法:
System.Type type = typeof(int);
在此, type是所获得的类型。
例子 :
// C# program to illustrate the
// concept of typeof operator
using System;
class GFG {
// Here store Type as a field
static Type a = typeof(double);
// Main method
static void Main()
{
// Display the type of a
Console.WriteLine(a);
// Display the value type
Console.WriteLine(typeof(int));
// Display the class type
Console.WriteLine(typeof(Array));
// Display the value type
Console.WriteLine(typeof(char));
// Display the array reference type
Console.WriteLine(typeof(int[]));
}
}
输出:
System.Double
System.Int32
System.Array
System.Char
System.Int32[]
typeof运算符和GetType方法之间的区别
typeof Operator | GetType Method |
---|---|
It takes the Type itself as an argument and returns the marked type of the argument. | It only invoked on the instance of the type. |
It is used to get a type that is known at compile-time. | It is used to obtain the type of an object at run-time. |
It cannot be used on an instance. | It can be used on instance. |
例子:
// C# program to illustrate the
// difference between typeof
// operator and GetType method
using System;
public class GFG {
// Main method
static public void Main()
{
string s = "Geeks";
// using typeof opertor
Type a1 = typeof(string);
// using GetType method
Type a2 = s.GetType();
// checking for equality
Console.WriteLine(a1 == a2);
// taking a type object
object obj = "Hello";
// using typeof operator
Type b1 = typeof(object);
// using GetType method
Type b2 = obj.GetType();
// checking for equality
// it will return False as
// GetType method is used
// to obtain run-time type
Console.WriteLine(b1 == b2);
}
}
输出:
True
False
说明:在这里, Type b1 = typeof(object);
这将返回System.Object,但Type b2 = obj.GetType();
将返回System.String 。因为,在编译时仅创建对象类型引用,但是在运行时,字符串(“ Hello”)实际上存储在其中。