You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 .csproj file (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.json file.
  • Add "/p:AllowUnsafeBlocks=true" to the args array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:53:11