首页 > Windows开发 > 详细

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

时间:2017-06-27 16:46:36      阅读:426      评论:0      收藏:0      [点我收藏+]

Object.GetType()与typeof的区别

//运算符,获得某一类型的 System.Type 对象。
Type t = typeof(int);

//方法,获取当前实例的类型。
 int i = 10;
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);
                }
            }

 

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

原文:http://www.cnblogs.com/zmztya/p/7085939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!