2024年3月11日发(作者:)
关于Instance()与Instance()方法的区别
呃``最近用惯了Instance()和Instance
好用,可是在看许多别人的源代码的时候,大多数用了
("AssemblyName").CreateInstance("ClassName");的方法,忽然想研究一下
这两者 到底有什么区别,于是,打开msdn,查到了两个方法的介绍:
Instance 方法 (String)
使用区分大小写的搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。
Instance 方法 (Type)
使用与指定参数匹配程度最高的构造函数来创建指定类型的实例。
看完以后,忽然觉得说了跟没说一样。不知道是我文字理解能力有问题,还是它表达有问题。
于是,没办法,只好用Reflector看看源代码了。
ly位于里,CreateInstance()方法的源码是这样
的
tor也位于里,CreateInstance()方法的
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bin
dingAttr, Binder binder, object[] args, CultureInfo culture, object[] activatio
nAttributes)
{
Type type1 = eInternal(typeName, false, ignoreCase, false);
if (type1 == null)
{
return null;
}
//注意一下这一句,晕。。。。这里居然调用了Instance方法
return Instance(type1, bindingAttr, binder, args, cultu
re, activationAttributes);
}
源码如下
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(ourceString("No
tSupported_CreateInstanceWithTypeBuilder"));
}
if ((bindingAttr & ((BindingFlags) 0xff)) == t)
{
bindingAttr |= Instance |
| ce;
}
if ((activationAttributes != null) && ( > 0))
{
if (!halByRef)
{
throw new NotSupportedException(ourceStri
ng("NotSupported_ActivAttrOnNonMBR"));
}
if (!extful && (( > 1) || !
(activationAttributes[0] is UrlAttribute)))
{
throw new NotSupportedException(ourceStri
ng("NotSupported_NonUrlAttrOnMBR"));
}
}
try
{
obj1 = ((RuntimeType) yingSystemType).CreateInstanceIm
pl(bindingAttr, binder, args, culture, activationAttributes);
}
catch (InvalidCastException)
{
throw new ArgumentException(ourceString("Arg_Mu
stBeType"), "type");
}
return obj1;
}
一个facade模式,就解决了问题,而Instance()方法的代码,
下次再研究,先把facade补习一下,呵呵。


发布评论