zoukankan      html  css  js  c++  java
  • 动态反射

    这个节课带来的是反射,有很多人我想他肯定知道有反射但是他们都不会用。包括有1-2年开发经验的人。

    前期绑定和后期绑定就是使用的反射。

    其实反射就是using System.Reflection里面的 主要使用2个类:第1个类就是Type类 第2个类就是Assembly类。

    很多人就会问到Assembly这个类怎么使用。

    因为初学者都基本知道Type类怎么使用,Assembly类就不知道怎么使用了。

    接下来我们一起来看看代码

    我必须1个接口 1个类来继承接口 1个类来实现动态反射,1界面调用

    跟它们取了个名字:

    接口 : IMessageBox

    继承接口类 :MyMessageBox

    反射类 : MessageBoxFactory

    调用类 :Test->WinForm2

    以上里面只有一个方法我毕竟是演示与讲解,希望大家自己下去多多练习

    1:接口

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace MyTest.TestLib
     6 {
     7     public interface IMessageBox
     8     {
     9         string Show();
    10     }
    11 }
    12 

    2:继承接口类

    代码
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace MyTest.TestLib
     7 {
     8     public class MyMessageBox : IMessageBox
     9     {
    10         #region IMessageBox 成员
    11         //继承接口返回一个String,接口就不讲了。上一章讲过了
    12         public string Show()
    13         {
    14             return "Hello Word";
    15         }
    16 
    17         #endregion
    18     }
    19 }
    20 

    3:反射(抽象工厂)

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Reflection;
     6 
     7 namespace MyTest.TestLib
     8 {
     9     public class MessageBoxFactory
    10     {
    11         //动态反射
    12         public static IMessageBox MyMessageBoxFactory()
    13         {
    14             //一定要写清楚程序集(namespace)
    15             string path = "MyTest.TestLib";//指定程序集
    16             return (IMessageBox)Assembly.Load(path).CreateInstance(path + ".MyMessageBox");//指定程序集合->下面的类
    17         }
    18     }
    19 }
    20 

    界面调用类 WinForm2

     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel;
     4 using System.Data;
     5 using System.Drawing;
     6 using System.Linq;
     7 using System.Text;
     8 using System.Windows.Forms;
     9 using MyTest.TestLib;
    10 namespace Test
    11 {
    12     public partial class Form2 : Form
    13     {
    14         public Form2()
    15         {
    16             InitializeComponent();
    17         }
    18 
    19         private void button1_Click(object sender, EventArgs e)
    20         {
    21             IMessageBox IMyMessageBox = MessageBoxFactory.MyMessageBoxFactory();
    22             MessageBox.Show(IMyMessageBox.Show());
    23         }
    24     }
    25 }
    26 
  • 相关阅读:
    AVR汇编初探之二《AVR的指令与汇编系统》
    Fedora 18 装完后干的事
    重建tempdb
    sqlserver 2008 r2 SqlClrProvider报错解析
    Analysis Memory In Sqlserver
    《设计模式之禅》学习笔记(七)
    容易弄错的繁体字
    《C Primer Plus》学习笔记
    什么是 Windows 能干而 Linux 干不了的事情
    MySQL中BLOB字段类型介绍
  • 原文地址:https://www.cnblogs.com/XiaoLongZhang/p/1662605.html
Copyright © 2011-2022 走看看