猿问

关于反射的一个问题,懂得进来帮我看下代码!!!!!!!!

程序

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

using System.Reflection;

namespace Test
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private object Invoke(string lpFileName, string Namespace, string ClassName, string lpProcName)
        {
            try
            { // 载入程序集
                Assembly MyAssembly = Assembly.LoadFrom(lpFileName);
                Type[] type = MyAssembly.GetTypes();
                foreach (Type t in type)
                {// 查找要调用的命名空间及类
                    if (t.Namespace == Namespace && t.Name == ClassName)
                    {// 查找要调用的方法并进行调用
                        MethodInfo m = t.GetMethod(lpProcName);
                        if (m != null)
                        {
                            object o = Activator.CreateInstance(t);
                            return m.Invoke(o, null);
                        }
                        else MessageBox.Show(" 装载出错 !");
                    }
                }
            }//try
            catch (System.NullReferenceException e)
            {
                MessageBox.Show(e.Message);
            }//catch
            return (object)0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(" 点击获取字符串 " + Invoke("DataLogic.dll", "DataLogic", "Form1", "getArray").ToString());
        }
    }
}

被调用的DLL程序

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

namespace DataLogic
{
    public partial class Form1 : Form
    {
       

        public Form1()
        {
            InitializeComponent();

  }

         public string getArray()
        {

            string va = "aaaaaa";
            return va;
        }

我只是想反射得到getArray()方法里“aaaaaa”,不知道为什么object o = Activator.CreateInstance(t);报错,我不知道错在哪了,大家帮我看下。

千巷猫影
浏览 446回答 2
2回答

胡说叔叔

你的代码没有问题,我试过,再查查dll的引用,invoke的参数是否传对了。
随时随地看视频慕课网APP
我要回答