AppDomain.CreateInstance和Activator.CreateInstance有什么区别?

lok*_*oki 6 .net c# appdomain activator

我想问一个问题来实现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);
Run Code Online (Sandbox Code Playgroud)

例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;
}
Run Code Online (Sandbox Code Playgroud)

示例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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你能解释一下为什么我需要更多的方法或有什么区别?

小智 4

从 sscli2.0 源代码来看,AppDomain类中的“CreateInstance”方法调用始终将调用委托给Activator

(几乎静态的) Activator类的唯一目的是“创建”各种类的实例,而引入AppDomain是为了完全不同的(也许更雄心勃勃)的目的,例如:

  1. 轻量级的应用程序隔离单元;
  2. 优化内存消耗,因为 AppDomain 可以卸载。
  3. ...

正如 zmbq 所指出的,第一个和第三个示例很简单。我想您的第二个示例来自这篇文章,其中作者展示了如何使用 AppDomain 卸载过时的代理。