zoukankan      html  css  js  c++  java
  • 两种动态创建对象的方法

    1、如果要创建的对象,在一个assembly中,那么方法可以有很多。如这种方式:
                    System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(@"D:Programsvs.netInterfaceCominDebugCom.dll");
                    Type t 
    = ass.GetType("Com.Class1");
                    
                    
    string[] implCtorSig = {"System.String"};
                    Type[] ctorSigArr 
    = Type.GetTypeArray(implCtorSig);
                    System.Reflection.ConstructorInfo ctorInfo 
    = t.GetConstructor(ctorSigArr);            
                    
    object[] ctorArgs = {"1"};
                    
    object obj = ctorInfo.Invoke(ctorArgs);    
                    Com.IDict idict 
    = (Com.IDict)obj;
    2、如果对象在另一个assembly中,那么上述代码最后一行,会抛出一个invalid cast异常。而用下面的方式,是可以的:
                    System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(@"D:Programsvs.netInterfaceCominDebugCom.dll");
                    Type t 
    = ass.GetType("Com.Class1");
                    
    object[] ctorArgs = {"1"};
                System.Runtime.Remoting.ObjectHandle oh 
    = Activator.CreateInstance(ass.FullName,t.FullName,true,System.Reflection.BindingFlags.CreateInstance,null,ctorArgs,System.Globalization.CultureInfo.CurrentCulture,new Object[]{},null);
        Com.IDict dict 
    = (Com.IDict)(oh.Unwrap());

  • 相关阅读:
    Hibernate中使用@Lob 注解保存String[] 问题
    具体解释Java虚拟机类载入
    POJ 2631 Roads in the North(树的直径)
    MySQL远程訪问的两个问题
    org.hibernate.LazyInitializationException could not initialize proxy-no Session的解决
    博客搬家啦!
    hdu 5015 233 Matrix (矩阵高速幂)
    Flink内存管理源代码解读之基础数据结构
    UML图与机房收费系统实例
    TextView设置成仅仅读
  • 原文地址:https://www.cnblogs.com/juqiang/p/45430.html
Copyright © 2011-2022 走看看