能否添加引用仅存在于内存中的程序集的类型?
如何引用仅存在于内存中的.NET类型?
尝试通过Add-Type创建一个仅存在于内存中的类型,接着找到它所属的程序集,再创建另一个继承该类型的新类型,代码如下:
Add-Type -TypeDefinition 'namespace MyNamespace { public class c {}}' $assembly = $([System.AppDomain]::CurrentDomain. GetAssemblies(). GetTypes() | ? {$_.Namespace -eq 'MyNamespace' } | % Assembly | Select-Object -Unique -First 1 ) Add-Type -TypeDefinition 'namespace MyNamespace {public class d : c {}}' ` -ReferencedAssemblies $assembly
执行上述代码会失败,报错信息如下:
Add-Type: C:\repro.ps1:12 Line | 12 | Add-Type -TypeDefinition 'namespace MyNamespace {public class d : c { … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | The value cannot be an empty string. (Parameter 'path')
报错原因是Add-Type需要查找程序集对应的文件路径,但该程序集仅存在于内存中,没有实际的文件路径,因此无法完成引用。
核心问题
能否引用仅存在于内存中的类型?
可行方案
目前仅当程序集保存到文件系统中时,才能实现类型引用,代码示例如下:
Remove-Item .\c.dll,.\d.dll -ErrorAction SilentlyContinue Add-Type ` -TypeDefinition 'namespace MyNamespace { public class c {}}' ` -OutputAssembly .\c.dll Add-Type -Path .\c.dll [MyNamespace.c]::new() Add-Type -TypeDefinition 'namespace MyNamespace {public class d : c {}}' ` -ReferencedAssemblies .\c.dll ` -OutputAssembly .\d.dll Add-Type -Path .\d.dll [MyNamespace.d]::new()
该方案先将第一个类型编译为磁盘上的程序集文件,后续创建继承类型时直接引用该文件路径,即可正常完成类型的定义与加载。
内容的提问来源于stack exchange,提问作者alx9r
相关产品推荐
相关产品推荐

