c# - AppDomain.CreateInstance 和 Activator.CreateInstance 有什么区别?

标签 c# .net 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);

例子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 是为完全不同的(也许更雄心勃勃的)引入的) 目的,例如:

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

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

关于c# - AppDomain.CreateInstance 和 Activator.CreateInstance 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9680966/

相关文章:

c# - 如何强制缩进 C# 条件指令?

c# - 将一个表单停靠到另一个表单上

c# - 在 Windows 7 中保留屏幕区域

c# - 如何将不可序列化的对象作为参数发送给代理方法。 MarshalByRefObject 包装器?

c# - Windbg 和查看 AppDomain 内容

c# - 为什么结构内部的匿名方法不能访问 'this' 的实例成员

c# - 使用带有 bool 值的 C# 维护 ASP.NET 3.5 中的 session 状态

c# - 检查未初始化的 DateTime 属性?

c# - 有没有办法从 System.Windows.Forms.HtmlElement 转换为 mshtml.IHTMLElemenet3?

asp.net - 防止 IIS 为单独的 ASP.Net AppDomain 重用工作进程