c# 之 System.Type.GetType()与Object.GetType()与typeof比较

Object.GetType()与typeof的区别

//运算符,获得某一类型的 System.Type 对象。
Type t = typeof(int); //方法,获取当前实例的类型。
int i = ;
Console.WriteLine(i.GetType());
//区别
Typeof()是运算符而GetType是方法
GetType()是基类System.Object的方法,因此只有建立一个实例之后才能被调用(也就是创建实例)
Typeof()的参数只能是lint,string,类,且不能是实例
得到结果的区别
(1)Typeof():得到一个class的Type
(2)GetType():得到一个class实例的Type

System.Type.GetType()的使用

Type type = System.Type.GetType("ConsoleApplication1.child");
Type type1 = System.Type.GetType("System.Int32");

Object.GetType()的小案例

public class Student
{
public Student()
{ }
public virtual string Id { get; set; }
public virtual string StudentNo { get; set; }
public virtual string Address { get; set; }
} public class StudentDTO
{
public StudentDTO()
{ }
public virtual string Id { get; set; }
public virtual string StudentNo { get; set; }
public virtual int TeacherId { get; set; }
}
//对student对象赋值
Student student = new Student();
student.Id = Guid.NewGuid().ToString();
student.Name = "张三";
student.Address = "福建";
//将student的值赋予studentdto
StudentDTO studentDTO = new StudentDTO();
studentDTO.Id = student.Id;
studentDTO.Name = student.Name; 改进:若是student的属性过多,那么可以通过此方法减少许多代码
foreach (var item in student.GetType().GetProperties()) //返回Student的所有公共属性
{
var value = item.GetValue(student, null); //返回属性值
var setobj = studentDTO.GetType().GetProperty(item.Name); //搜索具有指定属性名称的公共属性
if (value != null && setobj != null)
{
setobj.SetValue(studentDTO, value, null);
}
}
上一篇:JDBC对Mysql utf8mb4字符集的处理


下一篇:Java 虚拟机 - GC 垃圾回收机制分析