zoukankan      html  css  js  c++  java
  • 反射

    1.普通实例化类

      IDBHelper dbhelper = new DBHelper();//实例化一个接口
      dbhelper.Query();//打印接口内容

    2.利用反射实例化

      App.config:

      <add key="sel" value="Ruanmou.DB.Sqlserver,Ruanmou.DB.Sqlserver.DBHelper"/>

      Program.cs:

      string nameSpace = ConfigurationManager.AppSettings["sel"];
      string [] nameSpaceArray = nameSpace.Split(',');

      Assembly assembly = Assembly.Load(nameSpaceArray[0]);//反射的入口

      Type type = assembly.GetType(nameSpaceArray[1]);//基于类的完整名称找出类型
      Object oDBHelper = Activator.CreateInstance(type);//实例化
      IDBHelper dbhelperReflection = (IDBHelper)oDBHelper;//强行转换
      dbhelperReflection.Query();//打印

      可以通过config文件而达到动态实例化的功能

      

      如将<add key="sel" value="Ruanmou.DB.Sqlserver,Ruanmou.DB.Sqlserver.DBHelper"/>

      修改为<add key="sel" value="Ruanmou.DB.MySql,Ruanmou.DB.MySql.DBHelper"/>

      从而改变实例化的接口为MySql库

      

     3.利用反射调用各种函数

      函数代码如下:

    namespace Ruanmou.DB.Sqlserver
    {
        public class ReflecctionTest
        {
            public void show1()
            {
                Console.WriteLine("这是{0}的show1", this.GetType().FullName);
            }
            public void show2(int i)
            {
                Console.WriteLine("这是{0}的show2,带参数i={1}", this.GetType().FullName,i);
            }
            public void show3(int i,int s)
            {
                Console.WriteLine("这是{0}的show3,带参数i={1},带参数s={2}", this.GetType().FullName,i,s);
            }
            public void show4(int i, string s)
            {
                Console.WriteLine("这是{0}的show4,带参数i={1},带参数s={2}", this.GetType().FullName, i, s);
            }
            public void show5()//show5测试重载
            {
                Console.WriteLine("这是{0}的show5", this.GetType().FullName);
            }
            public void show5(int i)
            {
                Console.WriteLine("这是{0}的show5,带参数i={1}", this.GetType().FullName, i);
            }
            public void show5(int i, int s)
            {
                Console.WriteLine("这是{0}的show5,带参数i={1},带参数s={2}", this.GetType().FullName, i, s);
            }
            public void show5(int i, string s)
            {
                Console.WriteLine("这是{0}的show5,带参数i={1},带参数s={2}", this.GetType().FullName, i, s);
            }
            private void show6() //私有函数
            {
                Console.WriteLine("这是{0}的show6", this.GetType().FullName);
            }
        }
    }
    

      反射调用函数如下:

               Assembly assembly = Assembly.Load("Ruanmou.DB.Sqlserver");//反射的入口
                Type type = assembly.GetType("Ruanmou.DB.Sqlserver.ReflecctionTest");//基于类的完整名称找出类型
                Object oDBHelper = Activator.CreateInstance(type);//实例化
                //ReflecctionTest dbhelperReflection = (ReflecctionTest)oDBHelper;//强行转换
                //dbhelperReflection.show1();//打印
                foreach(MethodInfo method in oDBHelper.GetType().GetMethods())//查看函数代码
                {
                    Console.WriteLine(method.Name);
                }
                MethodInfo show1 = type.GetMethod("show1");
                show1.Invoke(oDBHelper, null);
    
                MethodInfo show2 = type.GetMethod("show2");//带一个int参数
                show2.Invoke(oDBHelper, new Object[] { 1});
    
                MethodInfo show3 = type.GetMethod("show3");//带两个int参数
                show3.Invoke(oDBHelper, new Object[] { 1,2 });
    
                MethodInfo show4 = type.GetMethod("show4");//带一个int,一个string参数
                show4.Invoke(oDBHelper, new Object[] { 1, "hello" });
    
                //对象带有多个show5函数,所以这个方法会报错,匹配不明确
                //MethodInfo show5 = type.GetMethod("show5");
                MethodInfo show5_1 = type.GetMethod("show5",new Type[] { });//寻找无参show5函数
                show5_1.Invoke(oDBHelper,null);
    
                MethodInfo show5_2 = type.GetMethod("show5",new Type[] { typeof(int)});//带一个int参数
                show5_2.Invoke(oDBHelper, new Object[] { 1 });
    
                MethodInfo show5_3 = type.GetMethod("show5", new Type[] { typeof(int),typeof(int) });//带两个int参数
                show5_3.Invoke(oDBHelper, new Object[] { 1, 2 });
    
                MethodInfo show5_4 = type.GetMethod("show5", new Type[] { typeof(int),typeof(string) });//带一个int,一个string参数
                show5_4.Invoke(oDBHelper, new Object[] { 1, "hello" });
    
                //破坏规则,调用类的私有函数
                MethodInfo show6 = type.GetMethod("show6", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                show6.Invoke(oDBHelper, null);
    
                Console.ReadLine();

     4.泛型+反射实现数据库所有表的查询语句

      1)建表User和Book

        

      且表名、表内属性名与Model内部类相同

    public class User
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Sex { get; set; }
        }
    public class Book
        {
            public int ID { get; set; }
            public string BookName { get; set; }
            public string Writer { get; set; }
            public DateTime PubDate { get; set; }
        }

      2)泛型函数如下

            public T QueryDomain<T>(int id)
            {
                Type type = typeof(T);//获取类型
                string columns = string.Join(",",type.GetProperties().Select(p=>string.Format("{0}", p.Name)));//产生select的属性名,用逗号连接
                string dbName = "study.dbo.[" + type.Name+"]";
                string sql = string.Format("select {0} from {1} where ID={2}",columns,dbName,id);//编写查询语句
                using (SqlConnection conn = new SqlConnection(Connstr))//实例化conn
                {
                    SqlCommand comm = new SqlCommand(sql,conn);
                    conn.Open();
                    SqlDataReader reader = comm.ExecuteReader();
                    if(reader.Read())
                    {
                        T t = (T)Activator.CreateInstance(type);//实例化一个类
                        foreach (PropertyInfo prop in type.GetProperties())//循环获取属性
                        {
                            string PropertyName = prop.Name;//获取属性名
                            prop.SetValue(t, reader[PropertyName]);//赋值
                        }
                        return t;
                    }
                    reader.Close();
                    conn.Close();
                }
                return default(T);
            }

      3)调用函数如下

                DBHelper dbhelper = new DBHelper();
                User user = dbhelper.QueryDomain<User>(2);
                Console.WriteLine("ID={0}  名字是:{1}   性别:{2}",user.ID.ToString(),user.Name,user.Sex);
    
                Book book = dbhelper.QueryDomain<Book>(1234);
                Console.WriteLine("ID={0}  书名:{1}   作者:{2}   出版日期:{3}", book.ID.ToString(), book.BookName,book.Writer,book.PubDate.ToString());
    
                Console.ReadLine();
  • 相关阅读:
    2.12 使用@DataProvider
    2.11 webdriver中使用 FileUtils ()
    Xcode8 添加PCH文件
    The app icon set "AppIcon" has an unassigned child告警
    Launch Image
    iOS App图标和启动画面尺寸
    iPhone屏幕尺寸、分辨率及适配
    Xcode下载失败 使用已购项目页面再试一次
    could not find developer disk image
    NSDate与 NSString 、long long类型的相互转化
  • 原文地址:https://www.cnblogs.com/wskxy/p/9111310.html
Copyright © 2011-2022 走看看