我使用了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 }
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();
代码好像没问题
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();
}
添加引用