typeof 运算符用于获取某个类型的 System.Type 实例。typeof 运算符的实参必须是类型或类型形参的名称,如以下示例所示:
Console . WriteLine ( typeof ( List < string > ) ); // System.Collections.Generic.List`1[System.String]
void FF输出类型<T> ( ) => Console . WriteLine ( typeof ( T ) );
FF输出类型<int> ( ); // System.Int32
FF输出类型<Int32?> ( ); // System.Nullable`1[System.Int32]
FF输出类型<List<string>> ( ); // System.Collections.Generic.List`1[System.String]
FF输出类型<Dictionary<int , char>> ( ); // System.Collections.Generic.Dictionary`2[System.Int32,System.Char]
参数不能是需要元数据注释的类型。示例包括以下类型:
- dynamic
- string?(或任何可为 null 的引用类型)
这些类型不会直接在元数据中表示出来。这些类型包括描述基础类型的属性。在这两种情况下,都可以使用基础类型。可以使用 object 来代替 dynamic。可以使用 string 来代替 string?。
你还可以使用具有未绑定泛型类型的 typeof 运算符。未绑定泛型类型的名称必须包含适当数量的逗号,且逗号的数量比类型参数的数量少一。以下示例演示了具有未绑定泛型类型的 typeof 运算符的用法:
Console . WriteLine ( typeof ( Dictionary<,> ) ); // System.Collections.Generic.Dictionary`2[TKey,TValue]
表达式不能是 typeof 操作符的实参。要获取表达式结果的运行时类型的 System . Type 实例,请使用 Object . GetType 方法。
使用 typeof 运算符进行类型测试
使用 typeof 运算符来检查表达式结果的运行时类型是否与给定的类型完全匹配。以下示例演示了使用 typeof 运算符和 is 运算符执行的类型检查之间的差异:
static void Main(string[] args)
{
XueNaRui xue = new ( );
Console . WriteLine ( xue is XueNaRui ); // True
Console . WriteLine ( xue . GetType ( ) == typeof( XueNaRui ) ); // True
Console . WriteLine ( xue is Gou ); // True,因为雪纳瑞是狗的一种
Console . WriteLine ( xue . GetType ( ) == typeof ( Gou ) ); // False,因为 xue 的类确实不是 Gou
}
public class Gou
{
}
public class XueNaRui : Gou
{
}
重载
typeof 运算符不可被重载。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。