日期:2014-05-18  浏览次数:21133 次

为什么CreateInstance会返回NULL?
文件A:

using System;

using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;


using System.Threading;

using System.Windows.Forms;



namespace BackService
{

   

   
  public class Program
  {
   
   
  }
   

   
  public class MathClass//要定义为public
  {

  //私有变量
  public static int m_testi;

  private int x;

  private int y;

  //无参数的构造函数

  public MathClass()
  {

  this.x = 0;

  this.y = 0;


  m_testi = 0;

   

  }

   
  public int Add()
  {



  return m_testi;

  }





  }

  




   
}



文件B:

using System;

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

using System.Reflection;
using BackService;
using System.Windows.Forms;

namespace abcTest
{
  public partial class LoginView : Form
  {
  public LoginView()
  {
  InitializeComponent();
  this.ControlBox = false;
  }

 

  private void button1_Click(object sender, EventArgs e)
  {
   
   
  Assembly asm = Assembly.Load("BackService");
   
   

  object obj = asm.CreateInstance("BackService.MathClass");

   

  if (null == obj)
  {

  MessageBox.Show("动态创建对象失败!");

  }
  else
  {
  MessageBox.Show("创建好了!");
  }


  Type t = typeof(MathClass);

  MessageBox.Show("开始调用方法!");

  int result = (int)t.InvokeMember("Add", BindingFlags.InvokeMethod, null, obj, null);

  string aa;

  //aa.ToString(result);
  string strresult = result.ToString();

  MessageBox.Show(strresult);
   
   
   
   
  }

  private void button2_Click(object sender, EventArgs e)
  {
  Application.Exit();
  }


   

  //end class
  }
   
}


这个为什么会出异常呢?
object obj = asm.CreateInstance("BackService.MathClass");

如果改成 object obj = asm.CreateInstance("MathClass"