今天在整理项目代码时,发现 有这样一段代码
object commandInstance = Activator.CreateInstance(commandType);
然后发现一直没有用过,查过资料后发现大概就是
Activator.CreateInstance :使用与指定参数匹配程度最高的构造函数来创建指定类型的实例。
public virtual void ExecuteCommand(INotification note)
{
Type commandType = null;
lock (m_syncRoot)
{
if (!m_commandMap.ContainsKey(note.Name)) return;
commandType = m_commandMap[note.Name];
}
object commandInstance = Activator.CreateInstance(commandType);
if (commandInstance is ICommand)
{
((ICommand) commandInstance).Execute(note);
}
}
网上案例:
using System;
namespace ActivatorCreateInstance
{
/// <summary>
/// IObjcet 的摘要说明。
/// </summary>
public interface IObjcet
{
void printName();
}
}
//实现接口的类:比如在上例中,是交通工具类,这种类可以在扩展的时候添加,其它类的代码不用修改
using System;
namespace ActivatorCreateInstance
{
/// <summary>
/// ClassExam 的摘要说明。
/// </summary>
public class ClassExam:IObjcet
{
private string name="default name";
public ClassExam()
{
}
public ClassExam(string name)
{
this.name =name;
}
public void printName()
{
Console .WriteLine (this.ToString ()+"'s name is:");
Console .WriteLine (this.name );
}
}
}
//程序入口:
namespace ActivatorCreateInstance
{
/// <summary>
/// main 的摘要说明。
/// </summary>
public class main
{
public main()
{
}
public static void Main()
{
//用传递参数来得到一个类的实例
//用Activator .CreateInstance创建函数实例,默认的不带参数的构造函数
IObjcet obj=(IObjcet)Activator .CreateInstance(System.Type .GetType ("ActivatorCreateInstance.ClassExam,ActivatorExample" ),null);
//System.Type .GetType 命名空间.类名,程序集
obj.printName();
//调用ClassExam类的另一个带参数构造函数
IObjcet obj2=(IObjcet)System.Activator .CreateInstance (System.Type .GetType ("ActivatorCreateInstance.ClassExam,ActivatorExample" ),new string []{"seted new name"});
obj2.printName ();
}
}
}
拓展
1.用过类名创建Type实例创建指定类对象
object activator = Activator.CreateInstance(Type.GetType(“test”));
2.通过泛型指定类型创建指定类对象
object handle = Activator.CreateInstance();
3.通过类名创建Type实例并传入构造实参创建指定类对象
object handle = Activator.CreateInstance(Type.GetType(“test”),“abc”,“efg”);
但是在动态创建时,可能会动态使用到外部应用的DLL中类的实例,则此时需要进行反编译操作,使用Reflection命名控件下的Assembly类。
//先使用Assembly类载入DLL,再根据类的全路径获取类
object result = null;
Type typeofControl = null;
Assembly tempAssembly;
tempAssembly = Assembly.LoadFrom(vDllName);
typeofControl = tempAssembly.GetType(vFullClassName);
result = Activator.CreateInstance(typeofControl, objParam);