AppDomain.CreateInstance和Activator.CreateInstance有什么区别
本文关键字:CreateInstance 什么 区别 Activator AppDomain | 更新日期: 2023-09-27 18:27:31
我想问一个问题来了解AppDomain和Activator之间的区别,我通过AppDomain加载了我的dll。CreateInstance。但我意识到了创建实例的更多方法。因此,我在何时何地选择此方法?示例1:
// Use the file name to load the assembly into the current
// application domain.
Assembly a = Assembly.Load("example");
// Get the type to use.
Type myType = a.GetType("Example");
// Get the method to call.
MethodInfo myMethod = myType.GetMethod("MethodA");
// Create an instance.
object obj = Activator.CreateInstance(myType);
// Execute the method.
myMethod.Invoke(obj, null);
示例2:
public WsdlClassParser CreateWsdlClassParser()
{
this.CreateAppDomain(null);
string AssemblyPath = Assembly.GetExecutingAssembly().Location;
WsdlClassParser parser = null;
try
{
parser = (WsdlClassParser) this.LocalAppDomain.CreateInstanceFrom(AssemblyPath,
typeof(Westwind.WebServices.WsdlClassParser).FullName).Unwrap() ;
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
}
return parser;
}
示例3:
private static void InstantiateMyTypeSucceed(AppDomain domain)
{
try
{
string asmname = Assembly.GetCallingAssembly().FullName;
domain.CreateInstance(asmname, "MyType");
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine(e.Message);
}
}
你能解释一下为什么我需要更多的方法吗?或者有什么区别?
从sscli 2.0源代码来看,AppDomain类中的"CreateInstance"方法调用似乎总是将调用委托给Activator。
(几乎是静态的)Activator类的唯一目的是"创建"各种类的实例,而AppDomain的引入目的完全不同(可能更雄心勃勃),例如:
- 应用程序隔离的轻量级单元
- 优化内存消耗,因为AppDomains可以卸载
正如zmbq所指出的,第一个和第三个例子很简单。我想你的第二个例子来自这篇文章,作者在文章中展示了如何使用AppDomain卸载过时的代理。
第一个从程序集"example"创建类型为Example
的实例,并在其上调用MethodA
。
第三个在不同的AppDomain
中创建MyType
的实例
我不确定第二个,我不知道this
是什么,但在当前应用程序域中创建一个类似乎是,也就是说,它与第一个类似。