C# AppDomain.CreateInstance和Activator.CreateInstance之间有什么区别?
我想问一个问题来了解AppDomain和Activator之间的区别,我通过AppDomain.CreateInstance加载了我的dll。但我意识到更多的方法是创建实例。因此,我应该在何时何地选择这种方法? 例1:C# AppDomain.CreateInstance和Activator.CreateInstance之间有什么区别?,c#,.net,appdomain,activator,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"); //
// 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);
}
}
你能解释一下为什么我需要更多的方法或者有什么区别吗?第一个方法从程序集“Example”创建一个类型为
Example
的实例,并对其调用MethodA
第三个以不同的方式创建MyType
的实例
我不确定第二个,我不知道这是什么,但它似乎在当前应用程序域中创建了一个类-也就是说,它与第一个类似。从sscli2.0源代码看,类中的“CreateInstance”方法调用似乎总是将调用委托给 (几乎是静态的)Activator类的唯一目的是“创建”各种类的实例,而AppDomain的引入则是为了完全不同的目的(可能更雄心勃勃),例如: