typeof: The typeof operator is used to obtain the System.Type object for a type.
运算符,获得某一类型的 System.Type 对象。
Type t = typeof(int);
GetType: Gets the Type of the current instance.
方法,获取当前实例的类型。
int i = 10;
Console.WriteLine(i.GetType());
Type t = typeof(int);
string ss=(t.ToString());
int i = 10;
string tt =(i.GetType().ToString());
Console.WriteLine(ss + tt);
结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200421165247991.png)
区别:
Typeof()是运算符而GetType是方法
GetType()是基类System.Object的方法,因此只有建立一个实例之后才能够被调用(初始化以后)
Typeof()的参数只能是int,string,String,自定义类型,且不能是实例
GetType() 和typeof()都返回System.Type的引用。
TypeOf() 和GetType()的区别:
(1)TypeOf():得到一个Class的Type
(2)GetType():得到一个Class的实例的Type
override 一个方法的前担是这个方法在父类中:abstract or virtual, override
string str = string.Empty;
Type strType = str.GetType();
Type strTypeType = strType.GetType();
strType.ToString(); // returns "System.string"
strTypeType.ToString(); // returns "System.RuntimeType"
Type类
首先,对于预定义的类型(int,long,string等)、BCL中的类型(Console,IEnumerable等)和用户自定义类型(MyClass等),每种类型都有自己的成员和特性。
在BCL中,声明了一个叫做Type的抽象类,它被设计用来包含类型的特性。使用这个类的对象能让我们获取程序使用的类型的信息。
由于Type是抽象类,因此不能利用它去实例化对象。关于Type类:
对于程序中用到的每一个类型,CLR都会创建一个包含这个类型的Type类型的对象。
程序中用到的每一个类型都会关联到独立的Type类的对象。
不管创建的类型有多少个示例,只有一个Type对象会关联到所有这些实例。
获取Type对象
class MyClass
{
private int id;
private int age;
public int number;
public string Name1{get;set;}
public string Name2{get;set;}
public string Name3{get;set;}
public void Test1(){
}
public void Test2(){
}
}
//每一个类对应一个type对象,这个type对象存储了这个类有哪些方法、字段、成员
MyCLass my = new MyClass();//一个类中的数据是存储在对象中的,但是type对象之存储类的成员
Type type = my.GetType();//通过对象获取这个对象所属的类的Type对象
Console.WriteLine(type.Name);//获取类的名字
Console.WriteLine(type.Namespace);//获取所在的命名空间
Console.WriteLine(type.Assembly);//获取所在的程序集
//实际上,type对象和my对象是没有什么关系的
//仅仅是通过my对象获取对象所在类的Type对象而已
//获取字段
FieldInfo[] array = type.GetFields();//只能获取public字段
foreach(FieldInfo info in array)
Console.Write(info.Name + " ");
//输出为number
//获取属性
PropertyInfo[] array2 = type.GetProperties();
foreach(PropertyInfo info in array2)
Console.Write(info.Name + " ");
//输出为Name1 Name2 Name3
//获取方法
MethodInfo[] array3 = type.GetMethods();
foreach(MethodInfo info in array3)
Console.Write(info.Name + " ");
//输出为:
//get_Name1 set_Name1 get_Name2 set_Name2 get_Name3 set_Name3 Test1 Test2 ToString Equals GetHashCode GetType
//前面几个get和set方法是定义属性时系统所生成的
//最后的三个方法是继承自父类Object的方法