【问题标题】:what is the difference between AppDomain.CreateInstance and Activator.CreateInstance?AppDomain.CreateInstance 和 Activator.CreateInstance 有什么区别?
【发布时间】:2012-03-13 09:02:01
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net appdomain activator


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        • 2011-12-12
        • 2010-09-16
        • 2012-03-14
        • 2012-02-06
        相关资源
        最近更新 更多