反射

很久没有用,一下就忘记了..弄个备份,以后不会了回来看看...

1.测试的代码.把生成的exe拷贝到主程序的debug下面

View Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Up
{
    public partial class Form1 : Form
    {
        private bool flag = false;


        public bool Flag
        {
            get { return flag; }
            set { flag = value; }
        } 
 
        
        public Form1()
        {
            InitializeComponent();
        }
        

        private void Form1_Load(object sender, EventArgs e)
        {
            showMsg();
        }

        public void showMsg()
        {
            if (flag)
            {
                MessageBox.Show("哈哈..flag:" + flag.ToString());
            }
            else
            {
                MessageBox.Show("hello world..flag:" + flag.ToString());
            }
        }
 
    }
}


2.主程序

View Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //获取启动程序或者类的绝对路径
            string strpath = System.Environment.CurrentDirectory + "\\Up.exe";
            bool flag = comboBox1.Text == "true" ? true : false;
            //载入程序
            Assembly asbly = Assembly.LoadFile(strpath);
            //完全类名 up为 namespace,Form1为类名
            Type type = asbly.GetType("Up.Form1");
            //创建实例
            object obj = Activator.CreateInstance(type);
            //获取public属性
           PropertyInfo pinfo= type.GetProperty("Flag");
            //设置属性
           pinfo.SetValue(obj, flag, null);
            //找到public showmsg方法
            MethodInfo info = type.GetMethod("showMsg");
            //调用是无参数showmsg
           info.Invoke(obj, null);
            //调用是有参数showmsg(bool flag, string str)的方法
          // info.Invoke(obj, new Object[] { true,"哈哈哈" });
            
        }
    }
}

测试代码下载


作者:javaoraspx
出处:http://www.cnblogs.com/xyong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/xyong/p/2822386.html