zoukankan      html  css  js  c++  java
  • 反射

      想简化一些代码,就研究了一下反射,资料不少,感觉挺难,搞得似是而非。写了个小东西回顾一下反射的用法。

      建一个User类

     class User     {                        

    private string userid = "0001";         

    public string Userid        

     {             

     get { return userid; }            

     set { userid = value; }       

      }         

      private string userName = "aaa";           

         public string UserName{         

        get { return userName; }            

      set { userName = value; }         

    }         private string address = "bbb";       

      public string Address{            

      get { return address; }             

     set { address = value; }         

    }                 

    private string email = "ccc";       

      public string Email{             

    get { return email; }            

     set { email = value; }         

    }        

     private string phone = "ddd";        

     public string Phone         

    {              

    get { return phone; }            

     set { phone = value; }        

     }     }

      假如有个winform有个Phone属性,其值为88888888,可以这样来对其封装:

        Type type = typeof(User);

                  object obj = Activator.CreateInstance(type);              PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 

                User user=new User();  

               foreach (PropertyInfo p in props)

                {  

                   if (p.Name == "Phone")

                    {

                           p.SetValue(user"88888888");

                    }

                }

                Console.WriteLine(user.Phone+" "+user.Email+" "+user.Address);

                  Console.ReadKey();

  • 相关阅读:
    Windows 8 应用的页面导航(1)
    开发 Windows 8 Bing地图应用(6)
    Windows 8 应用的页面导航(2)
    Windows 8 生命周期管理(4)
    删除DataTable重复列,只针对删除其中的一列重复的行
    Silverlight 数据库 Silverlight Database
    广告费用 会计处理及其改进
    Query to Join Delivery Details and MTL Material Table
    SAVEPOINT
    SYNCHRONIZE
  • 原文地址:https://www.cnblogs.com/xuekai-to-sharp/p/3374376.html
Copyright © 2011-2022 走看看