zoukankan      html  css  js  c++  java
  • 通过类名动态创建对象(C#)

    在网上搜索通过类名动态创建对象,发现大多都是都是用System.Int32作为例子,并直接给出来了其完全限定名,对于怎样得到自定义类型的完全限定名的内容并不多,在此,我列出我对此的一点见解,希望对大家有所帮助。

    首先,给出一个比较常见的实例:
    1、自定义函数GetInstanceByName,用于通过指定类名创建相应的对象。

    private object GetInstanceByName(string className)
        {
                 object obj;
    
                 try
                 {
                        obj = Activator.CreateInstance(Type.GetType(className));
                        MessageBox.Show(obj.GetType().ToString());
                 }
    
    
                //创建Button实例的过程:Button btn=(Button)GetInstanceByName("System.Windows.Forms");
                //btn.Parent=this;
    
                //Assembly asm = Assembly.LoadWithPartialName(className);
                //try
                //{
                //    obj = Activator.CreateInstance(asm.GetType(className + ".Button"));
                //    MessageBox.Show(obj.GetType().ToString());
                //}   
             
                catch (Exception e)
                {
                      throw new Exception("动态创建实例失败 \n\n=> " + className, e);
                }
                return obj;
        }
    

    说明:className必须是完全限定名,如Int32的完全限定名是:
             System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 

             Button的完全限定名是:
             System.Windows.Forms.Button, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

             前面是类型名(如:System.Int32),后面是这个类型所在的Assembly的名字。

             注:对于系统默认的数据类型,只需类型名即可。

    2、调用函数GetInstanceByName得到相应的对象

    private void button1_Click(object sender, EventArgs e)
        {
                //Int32 myInt=(Int32)GetInstanceByName("System.Int32");
                  
                //得到Assembly名字的方法:
                //对于自定义的数据类型,需要通过Assemebly类得到程序集的全名(其实就是反射机制)
                   Assembly asm = Assembly.Load("Test");   //加载程序集,Test为程序集的名字
                   GetInstanceByName("Application1.Form1, " + asm.FullName);  //Application1.Form1表示命名空间Application1中的一个类"Form1"
                    MessageBox.Show(asm.FullName);
        }
    

    3、动态库调用

    Assembly assembly = Assembly.LoadFrom("MyTest.dll");
    Type type = assembly.GetType("MyTest.MyClass");
    object instance = Activator.CreateInstance(type);
    

    补充:加载程序集有两个函数,Assembly.Load()和Assembly.LoadFrom()。Assembly.Load的参数是程序集的名称,运行库会在本地目录和全局程序集高速缓存内搜索该程序集;Assembly.LoadFrom()的参数是程序集的完成路径名,不会在其它位置搜索该程序集。

    自定义ToolBox的实现会用到该技术。

    作者:Esion  来源:http://www.cnblogs.com/esion  转载请注明出处。

  • 相关阅读:
    VS中Debug和Release两个版本的区别
    Activex、OLE、COM、OCX、DLL之间的区别
    解决 C/C++ 程序执行一闪而过的方法
    调用规范stdcall、cdecl、fastcall、thiscall 、naked call的汇编理解
    Windows的MAX_PATH
    Servlet学习笔记(1)
    Eclipse使用JDBC小案例
    Oracle DB 总结(SQL)
    利用JS写一个计算平方的网页
    CSS部分语法1
  • 原文地址:https://www.cnblogs.com/esion/p/3071886.html
Copyright © 2011-2022 走看看