我想问一个问题来了解AppDomain和Activator之间的区别,我通过appdomain.CreateInstance加载了我的dll。但我意识到更多的方法来创建实例。因此,我何时何地选择这种方法? 示例 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);
}
}
您能解释一下为什么我需要更多方法或者有什么区别吗?
最佳答案
从 sscli2.0 源代码来看,它看起来像 AppDomain 中的“CreateInstance”方法调用。类总是将调用委托(delegate)给 Activator .
(几乎是静态的)Activator 类的唯一目的是“创建”各种类的实例,而 AppDomain 是为完全不同的(也许更雄心勃勃的)引入的) 目的,例如:
- 应用程序隔离的轻量级单元;
- 优化内存消耗,因为可以卸载 AppDomain。
- ...
第一个和第三个示例很简单,正如 zmbq 指出的那样。我猜你的第二个例子来自这个 post ,作者在其中展示了如何使用 AppDomain 卸载过时的代理。
关于c# - AppDomain.CreateInstance 和 Activator.CreateInstance 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9680966/