6

我想问一个问题来了解 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);
    }
}

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

4

2 回答 2

4

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

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

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

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

于 2012-03-13T13:14:54.367 回答
2

第一个Example从程序集“example”创建类型的实例,并调用MethodA它。

第三个创建一个MyType不同的实例AppDomain

第二个我不确定,我不知道是什么this,但它似乎在当前的应用程序域中创建了一个类 - 即它与第一个相似。

于 2012-03-13T09:11:26.053 回答