gpt4 book ai didi

c# - 如何带参数调用crossappdomaindelegate-Method

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:13 25 4
gpt4 key购买 nike

我想用需要参数的方法名称调用方法 crossappdomaindelegate。

例子:

myAppdomain.DoCallback(new CrossAppDomainDelegate(MyMethod));

private static void MyMethod(string myParam)
{
Console.Write("my param="+ myParam);
}

如何在 new 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;
}

最佳答案

这是在另一个 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 文件夹中)。

关于c# - 如何带参数调用crossappdomaindelegate-Method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35453881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com