码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-06-27 17:01:17      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:student   system   foreach   amp   cat   ati   调用   div   tostring   

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比较

标签:student   system   foreach   amp   cat   ati   调用   div   tostring   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!