關於Assembly.CreateInstance()與Activator.CreateInstance()方法
動態創建類對象,大多是Activator.CreateInstance()和 Activator.CreateInstance<T>()方法,非常好用,一般都用了 Assembly.Load("AssemblyName").CreateInstance ("ClassName");的方法,研究一下這兩者到底有什么區別,在msdn里,查到了兩個方法的介紹:
Assembly.CreateInstance 方法 (String)
使用區分大小寫的搜索,從此程序集中查找指定的類型,然后使用系統激活器創建它的實例。
Activator.CreateInstance 方法 (Type)
使用與指定參數匹配程度最高的構造函數來創建指定類型的實例。
看完以后,忽然覺得說了跟沒說一樣。不知道是我文字理解能力有問題,還是它表達有問題。
於是,沒辦法,只好用Reflector看看源代碼了。
System.Reflection.Assembly位於mscorlib.dll里,CreateInstance()方法的源碼是這樣的
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[]
activationAttributes)
{
Type type1 = this.GetTypeInternal(typeName, false, ignoreCase, false);
if (type1 == null)
{
return null;
}
//注意一下這一句,暈。。。。這里居然調用了Activator.CreateInstance方法
return Activator.CreateInstance(type1, bindingAttr, binder, args, culture, activationAttributes);
}
System.Activator也位於mscorlib.dll里,CreateInstance()方法的 源碼如下
public static object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
object obj1;
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type is TypeBuilder)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
}
if ((bindingAttr & ((BindingFlags) 0xff)) == BindingFlags.Default)
{
bindingAttr |= BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance;
}
if ((activationAttributes != null) && (activationAttributes.Length > 0))
{
if (!type.IsMarshalByRef)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR"));
}
if (!type.IsContextful && ((activationAttributes.Length > 1) || !(activationAttributes[0] is UrlAttribute)))
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR"));
}
}
try
{
obj1 = ((RuntimeType) type.UnderlyingSystemType).CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes);
}
catch (InvalidCastException)
{
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
}
return obj1;
}
===================================================================================
一個facade模式,就解決了問題,而System.Activator.CreateInstance()方法的代碼,下次再研究,先把facade補習一下,呵呵。
===================================================================================
DALFactory默認是每一層封裝到一個程序集(獨立項目)組件里。通過反射機制創建對象實例。
//從程序集創建對象實例
string path = System.Configuration.ConfigurationSettings.AppSettings["DAL"];//數據層的程序集名稱
return (IDbObject)Assembly.Load(path).CreateInstance(path+".DbObject");
如果你的數據層不是單獨的程序集,可以采用如下方法加載:
//使用與指定參數匹配程度最高的構造函數來創建指定類型的實例
string path = System.Configuration.ConfigurationSettings.AppSettings["DAL"];
string TypeName=path+".DbObject"
Type objType = Type.GetType(TypeName,true);
return (IDbObject)Activator.CreateInstance(objType);