You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否添加引用仅存在于内存中的程序集的类型?

如何引用仅存在于内存中的.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:57:17