2009年3月7日星期六

C# 通过类名动态创建对象

首先,给出一个比较常见的实例:
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);
}

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

没有评论:

wholesale retail company from china

achinaseller.com is a professional wholesale retail company, having our own factory with 5 years of wholesale retail experience. Achinaseller.com is also cooperating closely with many factories, so the price that we offer to the consumer is directly from the Chinese Factory. Without leaving your home, you could order your own products at achinaseller.com at the lowest price.
We service over 100,000 registered buyers, delivering to virtually every country in the world. Our warehouse and office are staffed by a young team of Chinese and Western staff.
Happy AchinaSeller buyers include frequent wholesale importers, famous ecommerce websites, eBay powersellers, retail shops and startup home import businesses. On a daily basis, we serve corporate buyers, drop-ship experts, home business Moms, and small bussiness wholesaler