如何在 C# 中获取父程序集中的引用列表。我在想一个加载到另一个程序中的 DLL,驱动程序需要在反射和序列化中使用一些父程序集引用。到目前为止,我还没有尝试任何东西,因为我不确定从哪里开始。
最佳答案
这是一个非常经典的反射问题,当您需要加载一个程序集并且该程序集包含引用时,这些引用未引用到调用程序集。
基本上,您应该在单独的应用程序域中加载程序集。
例如,您有一个带有类 ProxyType 的项目 ProxyDomain:
public class ProxyType : MarshalByRefObject
{
public void DoSomeStuff(string assemblyPath)
{
var someStuffAssembly = Assembly.LoadFrom(assemblyPath);
//Do whatever you need with the loaded assembly, e.g.:
var someStuffType = assembly.GetExportedTypes()
.First(t => t.Name == "SomeStuffType");
var someStuffObject = Activator.CreateInstance(someStuffType);
someStuffType.GetMethod("SomeStuffMethod").Invoke(someStuffObject, null);
}
}
并且在包含对 ProxyDomain 的引用的调用项目中,您需要加载程序集,执行 DoSomeStuff 并卸载程序集资源:
public class SomeStuffCaller
{
public void CallDoSomeStuff(string assemblyPath)
{
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
//Path to the directory, containing the assembly
setup.ApplicationBase = "...";
//List of directories where your private references are located
setup.PrivateBinPath = "...";
setup.ShadowCopyFiles = "true";
var reflectionDomain = AppDomain.CreateDomain("ProxyDomain", null, setup);
//You should specify the ProxyDomain assembly full name
//You can also utilize CreateInstanceFromAndUnwrap here:
var proxyType = (ProxyType)reflectionDomain.CreateInstanceAndUnwrap(
"ProxyDomain",
"ProxyType");
proxyType.DoSomeStuff(assemblyPath);
AppDomain.Unload(reflectionDomain);
}
}
关于c# - 如何在 C# 中动态加载父程序集中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15174884/