如何在Visual Studio Code中运行unsafe代码并解决编译报错?
Fixing "Unsafe code may only appear if compiling with /unsafe" in Visual Studio Code
I’ve dealt with this exact headache before—VS Code doesn’t have that convenient "Project > Properties" menu like the full Visual Studio, so we have to adjust the build settings manually. Here are a few straightforward ways to get your unsafe code compiling:
1. Edit your .csproj file (permanent fix)
This is the best approach if you’ll be working with unsafe code regularly:
- Locate your project’s
.csprojfile (it’s in the root folder of your project) and open it in VS Code. - Add the
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>line inside the<PropertyGroup>section. It should look something like this:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- This enables unsafe code --> </PropertyGroup> </Project>
- Save the file, and VS Code will automatically reload your project. Your unsafe code should compile without errors now.
2. Compile via .NET CLI (one-off or temporary fix)
If you don’t want to modify your project file, you can pass the unsafe flag directly when building or running:
- To build:
dotnet build /p:AllowUnsafeBlocks=true
- To run directly:
dotnet run /p:AllowUnsafeBlocks=true
3. Update your VS Code build task (for automated builds)
If you use VS Code’s built-in tasks to compile, tweak your tasks.json to include the unsafe flag:
- Open your
.vscode/tasks.jsonfile. - Add
"/p:AllowUnsafeBlocks=true"to theargsarray of your build task. Example:
{ "version": "2.0.0", "tasks": [ { "label": "build", "command": "dotnet", "type": "process", "args": [ "build", "${workspaceFolder}/YourProjectName.csproj", "/p:AllowUnsafeBlocks=true" // Add this line ], "problemMatcher": "$msCompile" } ] }
That’s all—any of these methods should resolve the "unsafe code" error you’re seeing.
内容的提问来源于stack exchange,提问作者Prakash Reddy Potlapadu
相关产品推荐
相关产品推荐

