繁体   English   中英

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

[英]what is the difference between AppDomain.CreateInstance and Activator.CreateInstance?

我想问一个问题来实现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”方法调用总是将调用委托给Activator

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM