我想用一个需要参数的方法名称调用crossappdomaindelegate方法。
示例:
myAppdomain.DoCallback(new CrossAppDomainDelegate(MyMethod));
private static void MyMethod(string myParam)
{
Console.Write("my param="+ myParam);
}
如何在新的CrossAppDomainDelegate(MyMethod ....)中传递参数?
更新 只是为了完成Maarten对我具体案例的回答: 我还添加了一个ResolveHandler来查找已加载的程序集。 就好像其他人有类似的问题一样。
_myNewAppDomain.AssemblyResolve += MyResolveEventHandler;
public static Assembly MyResolveEventHandler(Object sender, ResolveEventArgs args)
{
var dllName = args.Name.Split(',')[0];
var currentAppdomain = (AppDomain) sender;
var file = currentAppdomain.GetAssemblies().FirstOrDefault(f => f.FullName.Split(',')[0] == dllName);
return file;
}
答案 0 :(得分:1)
以下是在另一个AppDomain
中检索程序集中的类型的一种方法。
首先,定义一些虚拟类:
public class X1 { }
public class X2 { }
public class X3 { }
public class X4 { }
public class X5 { }
然后定义一个特定的类来加载程序集中的类型:
public class TypesProvider : MarshalByRefObject
{
public string[] RetrieveTypes()
{
return Assembly.GetExecutingAssembly().GetTypes().Select(x => x.FullName).ToArray();
}
public string[] RetrieveTypesForAnotherAssembly(string assemblyFile)
{
return Assembly.LoadFile(assemblyFile).GetTypes().Select(x => x.FullName).ToArray();
}
}
并使用该类从程序集中检索类型:
class Program
{
static void Main(string[] args)
{
var domain = AppDomain.CreateDomain("type-provider-appdomain");
var typeProviderInstance = domain.CreateInstanceAndUnwrap(typeof(TypesProvider).Assembly.FullName, typeof(TypesProvider).FullName) as TypesProvider;
if (typeProviderInstance != null)
{
Console.WriteLine("Types for the executing assembly");
var types = typeProviderInstance.RetrieveTypes();
foreach (var type in types)
{
Console.WriteLine(type);
}
var assemblyFile = new FileInfo("EntityFramework.dll").FullName;
Console.WriteLine("Types for assembly " + assemblyFile);
types = typeProviderInstance.RetrieveTypesForAnotherAssembly(assemblyFile);
foreach (var type in types)
{
Console.WriteLine(type);
}
}
Console.ReadLine();
}
}
TypesProvider的第一个用法将产生虚拟类
Types for the executing assembly
SO_3543881.Program
SO_3543881.TypesProvider
SO_3543881.X1
SO_3543881.X2
SO_3543881.X3
SO_3543881.X4
SO_3543881.X5
第二个调用将从EntityFramework程序集中生成所有类型(如果已将其放在bin文件夹中)。