typeof运算符返回作为其参数的任何类型的System.Type对象。通过这个对象,可以了解类型的特征。(对任何已知类型,只有一个System.Type对象。)你不能重载typeof运算符。
typeof运算符是一元运算符
typeof——返回已知类型的System.Type对象
Type是System命名空间中的一个类
Type t=typeof(SomeClass)
下面的代码使用typeof运算符以获取SomeClass类的信息,并打印出它的公有字段和方法的名称。
using System;
using System.Reflection;//使用反射命名空间来全面利用检测类型信息的功能
namespace typeof运算符的使用
{
class SomeClass
{
public int Field1;
public int Field2;
public void Method1()
{
Console.WriteLine("这是第一个方法");
}
public int Method2()
{
return 1;
}
}
class Program
{
static void Main(string[] args)
{
Type t = typeof(SomeClass);
FieldInfo[] fi = t.GetFields();
MethodInfo[] mi = t.GetMethods();
foreach (FieldInfo f in fi)
{
Console.WriteLine($"Field:{f.Name}");
}
foreach (MethodInfo m in mi)
{
Console.WriteLine($"Method:{m.Name}");
}
Console.ReadLine();
}
}
}
GetType方法也会调用typeof运算符,该方法对每个类型的每个对象都有效。下面的代码获取对象类型的名称。
class SomeClass
{ }
class Program
{
static void Main(string[] args)
{
SomeClass s = new SomeClass();
Console.WriteLine($"Type s:{s.GetType().Name}");
}
}
输出
Type s:SomeClass
nameof运算符
nameof运算符返回一个表示传入参数的字符串
nameof——返回用来表示变量、类型或者成员的字符串