zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#对象的后期绑定方法

c#方法对象 绑定 后期
2023-09-27 14:20:16 时间

  COM技术编程时,利用 CreateObject 函数可以做组件后期绑定,根据 COM 组件的类名字符串,创建类的实例,然后通过约定的接口访问实例。在 C# 编程环境中,也有类似的方法。
  首先我创建一个类库 TestInterface.dll 定义了一个接口 IMyInterface,这个接口有一个方法 ShowForm()。

namespace TestInterface
{
    public interface IMyInterface
    {
        void ShowForm();
    }
}

  然后,我创建一个实例类库 TestImpInterface.dll,定义了一个类 Class1,实现了上面这个接口:

namespace TestImpInterface
{
    public class Class1: IMyInterface
    {
        public void ShowForm()
        {
            (new Form1()).Show();
        }
    }
}

  最后,我创建一个 WinForm 应用 WindowsFormsApplication1.exe,引用了接口定义类库 TestInterface.dll,利用实例类库的文件路径名称和类名字符串,创建了这个实例,并利用其公开的接口调用了其中的功能。

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

        private void button1_Click(object sender, EventArgs e)
        {
            Assembly asm = Assembly.LoadFrom("C:\\Users\\Administrator\\Documents\\Visual Studio 2013\\TestImpInterface\\TestImpInterface\\bin\\Debug\\TestImpInterface.dll");
            IMyInterface t = (IMyInterface)asm.CreateInstance("TestImpInterface.Class1");
            t.ShowForm();
        }
    }
}