zoukankan      html  css  js  c++  java
  • c# 之 System.Type.GetType()与Object.GetType()与typeof比较

    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);
                    }
                }
  • 相关阅读:
    PHP (20140519)
    PHP (20140516)
    js(20140517)在JS方法中返回多个值的三种方法
    PHP (20140515)
    PHP (20140514)
    Java内网发送邮件
    每日一“酷”之Cookie
    每日一“酷”之Queue
    每日一“酷”之pprint
    每日一“酷”之copy
  • 原文地址:https://www.cnblogs.com/zmztya/p/7085939.html
Copyright © 2011-2022 走看看