首页新闻找找看学习计划

.Net 如何动态加载DLL创建对象

0
[已解决问题] 解决于 2011-12-26 18:00

我使用了CodeDom创建类一个对象的程序集:dClass.dll

测试的代码如下:

1         static void Main(string[] args)
2 {
3 string className = "codeDom.dClass";
4 Type t = Type.GetType(className + "," + Assembly.Load(className.Substring(0, className.LastIndexOf('.'))).FullName);//这里无法正常加载到程序集,获取的对象时NULL,导致以下代码无法运行.
5 object obj = Activator.CreateInstance(t);
6 Console.ReadLine();
7
8 }

请问如何加载程序集呢?!~

程序集的源代码如下:

 1 [Description("自动生成的类")]
2 public class dClass
3 {
4 // Fields
5 private int sId;
6 private string[] sName;
7
8 // Methods
9 public dClass();
10
11 // Properties
12 public int SID { get; set; }
13 }




小明冥的主页 小明冥 | 菜鸟二级 | 园豆:222
提问于:2011-12-26 12:03
< >
分享
最佳答案
0
1 string path = Environment.CurrentDirectory + "\\dClass.dll";
2 Assembly ass = Assembly.LoadFile(path);//把Load换成LoadFile
3 Type t = Type.GetType("codeDom.dClass," + ass.FullName);
4 object obj = Activator.CreateInstance(t);
5 Console.ReadLine();
小明冥 | 菜鸟二级 |园豆:222 | 2011-12-26 17:59
其他回答(2)
0

代码好像没问题

牛啊牛 | 园豆:16 (初学一级) | 2011-12-26 16:26
0

static void Main(string[] args)
        {
            Console.WriteLine("列出程序集中的所有类型");
            Assembly ass = Assembly.LoadFrom("ClassLib.dll");
            Type classPerson = null;
            Type[] mytypes = ass.GetTypes();
            foreach (Type t in mytypes)
            {
                Console.WriteLine(t.Name);

                if (t.Name == "ClassPerson")
                {
                    classPerson = t;
                }
            }

            Console.WriteLine("列出ClassPerson类中的所有方法");
            MethodInfo[] mif = classPerson.GetMethods();
            foreach (MethodInfo mf in mif)
            {
                Console.WriteLine(mf.Name);
            }

            Console.WriteLine("实例化ClassPerson,并调用SayHello方法");
            Object obj = Activator.CreateInstance(classPerson);
            Object objName = Activator.CreateInstance(classPerson, "litianping");
            MethodInfo msayhello = classPerson.GetMethod("SayHello");
            msayhello.Invoke(obj, null); //空参数实例构造
            msayhello.Invoke(objName, null); //带参数实例构造

            System.Console.ReadLine();

        }

 

 

添加引用

yhpStyle | 园豆:10 (初学一级) | 2011-12-26 17:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册