如何使用#if 决定在 C# 中为哪个平台编译 [英] How to use #if to decide which platform is being compiled for in C#

查看:33
本文介绍了如何使用#if 决定在 C# 中为哪个平台编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中有预定义的宏:

In C++ there are predefined macros:

#if defined(_M_X64) || defined(__amd64__)
    // Building for 64bit target
    const unsigned long MaxGulpSize = 1048576 * 128;// megabyte = 1048576;
    const unsigned long MaxRecsCopy = 1048576 * 16;
#else
    const unsigned long MaxGulpSize = 1048576 * 8;// megabyte = 1048576;
    const unsigned long MaxRecsCopy = 1048576;
#endif

它允许我设置常量来控制将使用的内存量.

Which allows me to set constants to control the amount of memory that will be used.

当然我可以逐字定义一个预处理器变量:

Of course I can define a preprocessor variable verbatim:

#define Is64bit 1

using System;
using System.Collections.Generic;

-稍后-

#if Is64bit
    // Building for 64bit target
    const long MaxGulpSize = 1048576 * 128;// megabyte = 1048576;
    const long MaxRecsCopy = 1048576 * 16;
#else
    const long MaxGulpSize = 1048576 * 8;// megabyte = 1048576;
    const long MaxRecsCopy = 1048576;
#endif

我找不到一种根据配置管理器中设置的值来检测平台的方法,这将允许命令行构建:

I cannot find a way to detect the platform based on the values set in the configuration manager which would allow for command line building:

set de=C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDEdevenv.exe
set sol=E:SomePath	omy.sln
"%de%" %sol% /build "Release|x86"
"%de%" %sol% /build "Release|x64"

有没有办法检测到这一点,还是我必须构建、更改平台并再次构建?

Is there a way to detect this or will I have to build, change platform and build again?

更新:当最后一个 32 位 Windows 7 工作站退役时,32/64 位问题成为一个有争议的问题,因此不再需要为两个平台进行编译.我认为尽管保留这个线程是值得的,因为这些概念可以帮助其他预处理器指令,例如针对 MS Office 与 Open Office.

Update: The 32/64 bit question became a moot point when the last of the 32bit Windows 7 workstations were retired so needing to compile for both platforms was no longer necessary. I think though it's worthwhile to retain this thread as the concepts can help with other preprocessor directives, targeting MS Office vs Open Office for example.

推荐答案

您可以将您想要的任何常量添加到 .csproj 文件中.这些可以放入条件属性组中,如下所示.

You can add any constants you want to the .csproj file. These can be put into conditional property groups like the one below.

 <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <DefineConstants>TRACE;X64</DefineConstants>
    ...
 </PropertyGroup>

对于我的 Release x64 版本,我定义了一个 X64 常量,我可以这样使用:

For my Release x64 build, I have defined a X64 constant that I can use like this:

#if X64

#endif

这篇关于如何使用#if 决定在 C# 中为哪个平台编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆