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

PowerShell中动态添加自定义类的可见性问题(无需编译DLL)

不编译DLL实现PowerShell中依赖类的动态加载

想要创建一组可扩展类型动态添加到PowerShell脚本中,同一目录下有三个文件:

// T.cs
namespace T;  
public class ObjectBase {  
    private static int _id = 0;  
    public int Id { get; set; }  
    public ObjectBase() => this.Id = ++_id;  
}
// T_Derived.cs 
using T;
namespace T.Derived;
public class TD : T.ObjectBase {
    public string Name { get; set; }
    public TD(string name) : base() => this.Name = name;
}
# T.ps1
Add-Type .\T.cs
Add-Type .\T_Derived.cs

运行脚本时,T.ObjectBase能成功加载,但TD类报错:error CS0234: The type or namespace name 'ObjectBase' does not exist in the namespace 'T' (are you missing an assembly reference?),需要在不编译为DLL的前提下让第一个类对第二个类可见。


方法1:一次性加载所有依赖的C#文件

每次调用Add-Type会生成独立的临时程序集,分开加载时第二个编译过程无法访问第一个程序集的类型。把两个文件一次性传给Add-Type,它们会被编译到同一个程序集中,依赖关系自然生效:

# 修改后的T.ps1
Add-Type -Path .\T.cs, .\T_Derived.cs

方法2:显式引用第一个类的程序集

如果需要分步骤加载,可以通过-PassThru参数获取第一个类生成的程序集,然后在加载第二个类时通过-ReferencedAssemblies引用它:

# 修改后的T.ps1
# 加载基类并获取其程序集
$baseAssembly = Add-Type -Path .\T.cs -PassThru | Select-Object -ExpandProperty Assembly
# 加载派生类时引用基类的程序集
Add-Type -Path .\T_Derived.cs -ReferencedAssemblies $baseAssembly

内容的提问来源于stack exchange,提问作者bob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:57:37