我正在尝试在 .Net 中动态创建一个程序集。但是,我似乎无法弄清楚如何让 CodeBase 属性返回一个值。下面是一个例子:
var assemblyName = new AssemblyName
{
Name = "Whatever",
CodeBase = Directory.GetCurrentDirectory()
};
var assemblyBuilder = AppDomain.CurrentDomain
.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("WhateverModule", "Whatever.dll");
var typeBuilder = moduleBuilder.DefineType("WhateverType", TypeAttributes.Public);
var type = typeBuilder.CreateType();
assemblyBuilder.Save("Whatever.dll");
var codeBase = type.Assembly.CodeBase; // throws the below exception
System.NotSupportedException was unhandled
Message=The invoked member is not supported in a dynamic assembly.
Source=mscorlib
StackTrace:
at System.Reflection.Emit.InternalAssemblyBuilder.get_CodeBase()
at Stupid.Program.Main(String[] args) in C:\Users\Walking Disaster\Documents\Visual Studio 10\Projects\Lingual.Proxy\Stupid\Program.cs:line 25
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
谁能看到我做错了什么?
说明:我正在尝试使用在运行时生成测试方法的插件来扩展 NUnit。它通过获取一系列 Action 委托(delegate)来实现这一点。不幸的是,反射已经深入到框架中,所以我不得不为每个 Action 委托(delegate)发出一个带有方法的类。当我仅使用 NUnitTestMethod 类时,这工作正常,但是当我使用 NUnitTestFixture 时,它会失败,因为它尝试从程序集中读取 CodeBase。我不想创建一个物理组件,但这个项目是一个又一个的妥协。
最佳答案
我认为异常原因是 CodeBase 对动态汇编毫无意义。来自 MSDN:
如果你重新加载程序集,它不会抛出异常:
var assemblyName = new AssemblyName
{
Name = "Whatever",
CodeBase = Directory.GetCurrentDirectory()
};
var assemblyBuilder = AppDomain.CurrentDomain
.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(
"WhateverModule", "Whatever.dll");
var typeBuilder =
moduleBuilder.DefineType("WhateverType", TypeAttributes.Public);
var type = typeBuilder.CreateType();
assemblyBuilder.Save("Whatever.dll");
var assembly = Assembly.LoadFrom("Whatever.dll");
var codeBase = assembly.CodeBase; // this won't throw exception
关于c# - 无法从动态生成的程序集中访问 CodeBase,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2614914/