Home > Article > Development Tools > How to write and debug .net projects with vscode
Installing plug-ins
Using VSCode to write dotnet core projects. In addition to its default functions, I recommend installing some very unique features, and Useful extensions, it is precisely because of VSCode's plug-in mechanism that it becomes more powerful and meets our various needs.
1. C# language extension
This is necessary to use VSCode to write C# code. After installation, the debugger will be automatically downloaded when the .cs file is opened by default.
2. [C# XML Comment]
This plug-in can quickly help you add comments, choose to install it.
3. [C# Extensions]
This plug-in is highly recommended and can help you initialize the file content, including the corresponding namespace, etc. when creating the file.
There are also some other auxiliary classes, such as EditorConfig, Guildes, One Dark Theme, Project Manager, Setting Sync, etc.
Create a new multi-project solution
Open the command line tool and enter in the command line tool:
$:> dotnet new sln -o vscode_tutorial //在当前目录下 创建名为vscode_tutorial
The above command uses dotnet sdk , create a new solution file. You can create it manually without the command line, but using dotnet new can more conveniently create dotnet core-related projects, as shown in the following figure:
After building the solution, we need to build the project, including a console project, a class library project and a unit test project.
First create a public class library project to store our business methods (assuming we are working on a real project) (note that it has been cd into the sln directory at this time)
$:> dotnet new classlib -o VSCodeTutorial.Common //在当前目录下新建类库项目VSCodeTutorial.Common $:> dotnet sln add VSCodeTutorial.Common/VSCodeTutorial.Common.csproj //将项目添加到解决方案中
In the same way, we create the console project and unit test project
$:> dotnet new console -o VSCodeTutorial.ConsoleApp $:> dotnet sln add VSCodeTutorial.ConsoleApp/VSCodeTutorial.ConsoleApp.csproj $:> dotnet new xunit -o VSCodeTutorial.UnitTest $:> dotnet sln add VSCodeTutorail.UnitTest/VSCodeTutorial.UnitTest.csproj
It should be noted here that the name of the control template is console, and for unit testing we use xunit.
At this time our project structure has been established. Let’s use VsCode to open the current directory to see the completed project structure, as shown in the figure below:
Add dependencies between projects
Use VsCode to open the project file VSCodeTutorial.ConsoleApp.csproj and add a reference to the Common project in it
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> <!--添加项目引用--> <ItemGroup> <ProjectReference Include="..\VSCodeTutorial.Common\VSCodeTutorial.Common.csproj" /> </ItemGroup></Project>
Open VSCodeTutorial as well .UnitTest.csproj project file, add a reference to the Common project in it
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup><!--nuget 上的类库引用--> <ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" /> <PackageReference Include="xunit" Version="2.2.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" /> </ItemGroup><!--本地项目引用--> <ItemGroup> <ProjectReference Include="..\VSCodeTutorial.Common\VSCodeTutorial.Common.csproj" /> </ItemGroup></Project>
Different from the above project, there are some additional dependencies here. You can just understand it here. If you add the dependencies of the nuget package, Just use PackageReference as above and fill in the class library name and version number.
After adding the dependencies, we use dotnet restore in the root directory to initialize it, or we can use the dotnet build command to try to compile it.
The project dependencies are shown in Figure 2:
Start writing code
The overall requirements of this project: I You need to open a console program. When running, the user needs to input an integer less than 50. After receiving this number, the console calculates the factorial of this number and outputs the result to the console.
After simple thinking, I decided to put the implementation of factorial into the Common project and perform unit testing on it. The test code was put into the UnitTest project
First we delete the unnecessary files in the previously generated project: Class1.cs in VsCodeTutorial.Common and UnitTest1.cs in VSCodeTutorial.UnitTest. Of course, you can also keep them.
In the first step, we create a new file MathHelper.cs in the VsCodeTutorial.Common project and add the following code to the file to implement our factorial. The code is relatively simple and will not be described in detail.
namespace VSCodeTutorial.Common{ public class MathHelper { /// <summary> /// 阶乘,本例中暂不考虑 溢出的问题哦 Factorial(n) = n*(n-1)*(n-2)...*1; /// </summary> /// <param name="n">输入参数n</param> /// <returns></returns> public static int Factorial(int n){ if(n <=0 ){ throw new System.ArgumentOutOfRangeException("n","参数错误,不能小于等于零"); } if(n == 1){ return 1; } return n*Factorial(n-1); } } }
The second step is to test this code to see if it has achieved our goal. Create a new file MathHelpTest.cs in the VSCodeTutorial.UnitTest project and add a method to test the Factorial function to the file, as follows Instructions:
using System; using VSCodeTutorial.Common; using Xunit; namespace VSCodeTutorial.UnitTest{ public class MathHelperTest { [Fact] public void TestFactorial() { //先测试一下边界的情况 int zero = 0 ; var exception = Assert.Throws<ArgumentOutOfRangeException>(() => MathHelper.Factorial(zero)); int one = 1; var oneResult = MathHelper.Factorial(one); Assert.Equal(1, oneResult); //再测一下正常的情况 int five = 5; var fiveResult = MathHelper.Factorial(five); Assert.Equal(5*4*3*2*1, fiveResult); int ten = 10; var tenResult = MathHelper.Factorial(ten); Assert.Equal(10*9*8*7*6*5*4*3*2*1, tenResult); } } }
Use the command line to run the unit test
Before configuring VSCode, I still recommend that you use the command line to run the unit test, which is conducive to more Good understanding of configuration content.
Enter the command in the root directory: dotnet test ./VSCodeTutorial.UnitTest/VSCodeTutorial.UnitTest.csproj View the running results:
很差劲会出现编码错误,而且这个错误暂时还没有办法解决..但是我猜单元测试通过了,这个问题相信在后续的版本中肯定会得到解决,事实上在Console项目中是可以解决输出乱码问题的。不过可喜的是在VSCode中运行单元测试是没有乱码的问题的。
使用VSCode 运行单元测试
首先当你打开项目的时候,VSCode 可能已经建议你配置一下相关的内容,如下图所示:
选择Yes, 会帮你新建这个一个目录和两个文件,luanch.json是用来执行调试程序的配置,而tasks.json则是配置各种任务的,其中运行单元测试就是一种任务。
首先我们打开tasks.json ,默认已经添加好了一个任务,如下所示:
{ "version": "0.1.0", "command": "dotnet", //全局命令,即所有的任务都使用这个命令,也可以在各个任务中设置 "isShellCommand": true, "args": [], "tasks": [ { "taskName": "build", //任务名称 当设置了主的command 之后这个taskName也会作为一个命令参数 "args": [ "${workspaceRoot}\\VSCodeTutorial.ConsoleApp\\VSCodeTutorial.ConsoleApp.csproj" ], "isBuildCommand": true, //一个解决方案只能设置一个编译任务,多设置了也是白搭,当然也能执行,只是不能利用快捷方式运行了 "problemMatcher": "$msCompile"//C#项目的problemMatcher } ]}
默认使用了全局命令行,这样可以在任务中省去配置dotnet命令,但是如果你的解决方案中包括多个项目需要不同的命令行编译方式,如果前端网站使用grunt打包资源,那么顶部应该留空,而在各个子任务中配置command。
还有如果存在多个编译项目时(如客户端和服务端在一个解决方案时),也应该把command配置在子任务中,并设置个性化的taskName以便区别,所以我推荐把command设置在任务中,下面我们修改一下以上代码,并添加一个运行单元测试的人。
{ "version": "0.1.0", "isShellCommand": true, "args": [], "tasks": [ { "taskName": "build_console", "command":"dotnet" "args": [ "build", //组成dotnet build //设置需要编译的项目,如果存在多个启动项目可以设置成解决方案文件(.sln),这里只有一个项目所以设置运行项目也可以 "${workspaceRoot}\\VSCodeTutorial.ConsoleApp\\VSCodeTutorial.ConsoleApp.csproj" ], "isBuildCommand": true, //设置是否编译项目 "problemMatcher": "$msCompile" }, { "taskName": "UnitTest", "command":"dotnet", "args": [ "test",//组成dotnet test 命令 "${workspaceRoot}\\VSCodeTutorial.UnitTest\\VSCodeTutorial.UnitTest.csproj" ], "isTestCommand": true,//设置为单元测试项目 "problemMatcher": "$msCompile" } ]}
上面的代码中,我将command命令移到了任务中,并给每个任务起了一个好识别的名字,现在这里一个有2个任务了
第一个任务build_console 运行时 会编译VSCodeTutorial.ConsoleApp项目及其依赖的项目
第二个任务UnitTest则是单元测试项目,运行dotnet test命令,这里有个特殊的设置就是"isTestCommand": true 标识为测试项目后可以通过快捷方式运行该命令
任务建好了,我们来运行任务把,windows按下 ctrl+shift+p,在弹出的对话框中输入:task 过滤命令可以得到以下的选项
选择任务:运行测试任务 这条来运行我们之前编写好的单元测试项目,可以看到运行成功的情况,如下图所示:
这里中文显示正常,没有乱码哦,但是我不知道是什么原因..就是这么神奇
对于经常执行的任务,可以通过设置键盘快捷方式来方便调用,可以看到我分别设置了ctrl+shift+t 运行测试任务ctrl+shift+b 运行编译任务,ctrl+shift+r 启动选择任务,大家可以根据自己的喜好来设置。
开始编写控制台代码
打开VSCodeTutorial.ConsoleApp项目中的Program.cs文件,修改其中的代码,如下所示:
using System; using VSCodeTutorial.Common; namespace VSCodeTutorial.ConsoleApp{ class Program { static void Main(string[] args) { while(true) { Console.WriteLine("请输入一个小于10的数字,回车结束:"); string input_str = Console.ReadLine(); if(int.TryParse(input_str ,out var input_int)) { if(input_int>0 && input_int<=10){ int result = MathHelper.Factorial(input_int); Console.WriteLine("你输入的数字是{0},它的阶乘结果是{1},退出请按ctrl+c,按其他键再试一次", input_int,result); Console.ReadKey(); } } else{ Console.WriteLine("输入的字符不是有效的数字"); } } } } }
代码比较 简单,就不做解释了,我们直接来看运行的结果,这里顺便提一下啊,在我们之前做的众多工作之后,我们这里编写代码有美美哒的智能提示哦,如下图所示:
好,再根目录下输入以下命令运行ConsoleApp
$:> dotnet run -p ./VSCodeTutorial.ConsoleApp/VSCodeTutorial.ConsoleApp.csproj
也可以在VSCodeTutorial.ConsoleApp 目录下直接运行dotnet run 命令即可.
结果运行还是乱码中,但是这次我们有办法解决,我们在控制台代码中添加一句代码即可onsole.OutputEncoding = Encoding.UTF8
using System; using System.Text; using VSCodeTutorial.Common;namespace VSCodeTutorial.ConsoleApp{ class Program { static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; // 设置控制台编码 while(true) { Console.WriteLine("请输入一个小于10的数字,回车结束:"); string input_str = Console.ReadLine(); if(int.TryParse(input_str ,out var input_int)) { if(input_int>0 && input_int<=10){ int result = MathHelper.Factorial(input_int); Console.WriteLine("你输入的数字是{0},它的阶乘结果是{1},退出请按ctrl+c,按其他键再试一次",input_int,result); Console.ReadKey(); } } else{ Console.WriteLine("输入的字符不是有效的数字"); } } } } }
使用dotnet build编译后,再次运行Console项目看到了我们期望的界面
程序运行正确,当然了,我们都跑过单元测试了不是。。
开始调试程序
如下图提示操作:
终于轮到我们之前生成的launch.json文件出场了,先来看下它的代码,代码中已经添加了配置的说明
{ "version": "0.2.0", "configurations": [ { "name": ".NET Core Launch (console)", //配置名称 可以改成更好识别的名字 "type": "coreclr", // .net core类型的调试 "request": "launch", //调试方式 不用改 "preLaunchTask": "build", // 前置任务,这里是编译,但是默认的编译任务,已经被我改了名字了,所以这里要改一下哦 "program": "${workspaceRoot}\\VSCodeTutorial.ConsoleApp\\bin\\Debug\\netcoreapp1.1\\VSCodeTutorial.ConsoleApp.dll", //需要调试的DLL的位置 "args": [], //额外的参数 "cwd": "${workspaceRoot}\\VSCodeTutorial.ConsoleApp", //工作目录 "console": "internalConsole", //控制台模式,这里是内嵌控制台,一会要改成外置的,不然没法交互输入 "stopAtEntry": false, "internalConsoleOptions": "openOnSessionStart" }, { "name": ".NET Core Attach", //名称 "type": "coreclr", //类型 "request": "attach", //使用附加的方式 "processId": "${command:pickProcess}" //附加的进程ID } ]}
根据实际情况,需要对上面的配置进行以下变更,变更的部分已经添加了注释,附加调试不是本文的重点,就不改了
{ "version": "0.2.0", "configurations": [ { "name": "调试ConsoleApp", //修改下命令 "type": "coreclr", "request": "launch", "preLaunchTask": "build_console", //修改前置任务名和task.json中配置一致 "program": "${workspaceRoot}\\VSCodeTutorial.ConsoleApp\\bin\\Debug\\netcoreapp1.1\\ VSCodeTutorial.ConsoleApp.dll", "args": [], "cwd": "${workspaceRoot}\\VSCodeTutorial.ConsoleApp", "externalConsole":true, //使用外置的控制台 "stopAtEntry": false, "internalConsoleOptions": "openOnSessionStart" }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" } ] }
修改完成后,我们点击运行按钮可以开始调试了,调试的方式和使用VS是一致的,快捷键为F5 F10 F11
完成!
相关文章教程推荐:vscode教程
The above is the detailed content of How to write and debug .net projects with vscode. For more information, please follow other related articles on the PHP Chinese website!