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

JAD*_*JAD 5 .net c# winforms visual-studio-code

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

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

从市场上安装了以下扩展:

在此处输入图片说明

我试过的

1个

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

类型或名称空间“窗体”在名称空间“ System.Windows”中不存在

因此,我尝试使用NuGet Package Manager: Add Package命令添加此文件,但是在这里找不到包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>
Run Code Online (Sandbox Code Playgroud)

但是在运行时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.
Run Code Online (Sandbox Code Playgroud)

并且在运行时给出以下异常:

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.
Run Code Online (Sandbox Code Playgroud)

2

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

我觉得这个问题困扰着XY问题。我是C#和.NET的新手,所以我不确定我哪里失败了,我尝试做的事情是否可能。

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

Pav*_*hin 8

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

dotnet new winforms
Run Code Online (Sandbox Code Playgroud)

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

dotnet new wpf
Run Code Online (Sandbox Code Playgroud)

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

PS:用 dotnet 测试3.0.100-preview-010184