c# - 使用 `dotnet new` 在 C# 中创建 Windows 窗体应用程序

标签 c# .net winforms visual-studio-code

我正在尝试在 Visual Studio Code 2017 中创建一个(简单的)Windows 窗体应用程序。遗憾的是我无法使用完整的 VS 版本,所以我没有创建新项目的菜单选项。

之前,我通过从 VSC 的终端运行 dotnet new console 创建了控制台项目。但是,我无法让它与表单应用程序一起使用。

以下扩展是从 Marketplace 安装的:

enter image description here

我尝试过的:

1

创建控制台应用程序,并引用 using System.Windows.Forms;:但是,这需要我引用此命名空间:

The type or namespace 'Forms' does not exist in the namespace "System.Windows"

所以我尝试使用 NuGet 包管理器:添加包 命令添加它,但在这里我找不到包 System.Windows.Forms

我最后想到的是手动添加对 .csproj 文件的引用:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="10.0.3"/>
    <PackageReference Include="System.Windows.Forms" HintPath = "\..\WINDOWS\Microsoft.NET\Framework\v4.0.30319"/>
  </ItemGroup>
</Project>

但是在运行 dotnet restore 时会给出警告:

warning NU1604: Project dependency System.Windows.Forms does not contain an inclusive lower bound. Include a lower bound in the dependency version to ensure consistent restore results.
warning NU1701: Package 'System.Windows.Forms 4.0.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.

运行时出现以下异常:

System.BadImageFormatException: Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058) ---> System.BadImageFormatException: Cannot load a reference assembly for execution.

2

创建一个 .cs 文件,并使用 csc 编译它。这样我就可以使用 Forms,但是我失去了 dotnet 处理其他依赖项的功能。

问题

我觉得这个问题存在 XY 问题。我是 C# 和 .NET 的新手,所以我不确定我哪里失败了,我想做的事情是否可行。

所以我的问题是,如何使用 dotnet new 命令创建 Windows 窗体应用程序?

最佳答案

从 dotnet 3.0 开始,您只需运行以下命令来初始化 WinForms 应用程序:

dotnet new winforms

要初始化 wpf 应用程序,只需运行:

dotnet new wpf

您可以通过运行 dotnet newdotnet new --help(这两个命令产生相同的输出)来查看 dotnet 3.0 的所有可用项目类型。

附注:使用 dotnet 3.0.100-preview-010184 进行测试。

关于c# - 使用 `dotnet new` 在 C# 中创建 Windows 窗体应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46582847/

相关文章:

C#:InvalidCastException 误导性消息背后的原因

.net - 我是否应该在 HttpWebResponse 上调用 Close,即使它在 using 语句中?

winforms - 如何在 Winforms 中制作 "popup"(提示、下拉、弹出)窗口?

c# - 如何检查两个控件是否在 Windows 窗体中重叠

c# - 使用 RegEx 提取所有参数

c# - CE 6.0/.NET CF 3.5 应用程序遇到严重错误 (MC3100)

c# - 如何取消 WPF TabControl 中的选项卡更改

.net - File.ReadAllBytes 抛出 IOException 表示该进程无法访问该文件,因为它正被另一个进程使用

c# - log4net 和 ELMAH 有什么区别?

c# - 将标签添加到 WinForm 中的文本框自定义用户控件