在 Visual Studio 2019 年,如何将我的项目程序集(或任何程序集)添加到 C# 交互窗格?

In Visual Studio 2019, how do I add my project assemblies (or any assemblies at all) to the C# interactive pane?

This question is not answered by the proposed duplicate. There is no "Initialize Interactive with Project" option when I right click my project.

我想在不创建另一个项目和编写控制台应用程序的情况下测试一些代码。我的项目包含对 System.Windows.Forms 的引用,我可以在我的项目中使用 Forms 命名空间,但是,由于以下错误,我无法在 C# interactive 中使用它:

> using System.Windows.Forms;
(1,22): error CS0234: The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)

我进行了一些调查,但找不到关于 Visual Studio 的此功能的太多信息。我想尝试用反射加载程序集,但加载程序集确实有效,C# interactive 仍然找不到 System.Windows.Forms 命名空间:

> Assembly.LoadFile("@C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref.1.0\ref\netcoreapp3.1\System.Windows.Forms.dll")`
using System.Windows.Forms;
(1,14): error CS0234: The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)

请注意,我确保 运行 #reset core 切换到 .NET Core 以匹配我尝试加载的程序集的版本。


无论是使用反射加载程序集还是使用更优雅的方法,如何在 Visual Studio 2019 的 C# Interactive 窗格中以可用的方式加载非默认程序集?

对于 C# Interactive,您可以使用 #r 指令直接加载 DLL。

只需执行以下命令:

> #r "C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref.1.0\ref\netcoreapp3.1\System.Windows.Forms.dll"

或更通用:

> #r "C:\YOUR\DLL\PATH"

之后,您应该能够从程序集中访问命名空间。

您还可以 运行 您的项目与 C# 交互。只需打开 C# interactive window,然后右键单击解决方案资源管理器中的项目,然后 select“Initialize Interactive with Project”,这也会加载所有在 C# 交互中的项目程序集。

祝你好运!