如何使用“<PlatformTarget>x86</PlatformTarget>”运行 .NET Core 应用程序

rhu*_*hes 5 c# .net-core visual-studio-code

我在 Visual Studio Code 中设置了一个基本的 C# 控制台应用程序,如下所示:

dotnet new console
dotnet restore
Run Code Online (Sandbox Code Playgroud)

然后我像这样构建:

dotnet build
Run Code Online (Sandbox Code Playgroud)

然后运行:

dotnet run
Run Code Online (Sandbox Code Playgroud)

这一切都按预期工作。如果我将平台目标更改为x86,当我再次构建和运行应用程序时,我会收到此错误:

Unhandled Exception: System.BadImageFormatException: Could not load file or assembly 'C:\temp\code\testx86_2\bin\Debug\netcoreapp2.0\testx86_2.dll'. An attempt was made to load a program with an incorrect format.

My files:

Program.cs:

using System;

namespace testx86_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

testx86_2.csproj before setting the platform target:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

</Project>
Run Code Online (Sandbox Code Playgroud)

testx86_2.csproj after setting the platform target:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

</Project>
Run Code Online (Sandbox Code Playgroud)

Versions:

  • Visual Studio Code: 1.13.1
  • Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core

Rob*_*ert 1

添加--runtime win-x86到运行命令应该强制运行时以 32 位模式启动,即使使用 x64 版本的 dotnet cli 也是如此。

不需要<PlatformTarget>x86</PlatformTarget>,将开关添加到运行命令足以强制 x86 模式。我会删除 PlatformTarget,以便您可以更轻松地在 x86 / x64 之间进行更改。