【问题标题】:Conditional Compilation Constants for Web Site Project网站项目的条件编译常量
【发布时间】:2025-12-18 01:10:02
【问题描述】:

我有一个我继承的网站项目并正在尝试清理。它有一个超过 10,000 个位置的 Common.cs 文件,所以我将它分成不同的文件。问题是在公共文件的顶部是一个#define UAT 语句,它在整个代码中用于做出某些配置决策,例如:

#if UAT
    using WCFServiceUAT;
#else
    using WCFServicePRD;
#endif

所以现在,当我去部署这个应用程序的生产版本时,我将不得不在许多不同的地方删除#define 语句,这似乎容易出错并且通常是个坏主意。 我正在寻找诸如条件编译常量之类的东西,我可以在其中定义一次,并让它影响整个项目。

这种类型的配置控制只在 C# 文件中使用。 #define 语句过去只需要在 Default.aspx.cs 和 Common.cs 中进行更改,但由于我的重组工作,它现在看起来更多了。尽管我的 site.master 文件可以根据某些配置更改标头,但这并不重要。

我已尝试更改项目的构建配置属性,但没有任何选项,例如条件编译常量,并且我假设我的项目类型不支持它。是否有任何其他方法可以将#define 放在全局项目级别,而不是放在每个文件的顶部?我找到的唯一解决方案是针对 Web 应用程序项目,并且基于 @987654321 @,我不相信我正在使用 Web 应用程序类型的项目,因为没有 .csproj 文件。

【问题讨论】:

  • 选择项目的属性,在第二页(BUILD)中,您应该会看到输入框“条件编译符号”,您可以在其中设置/删除 UAT 符号
  • 我是说它不存在。我有Before running startup page:Target FrameworkBuild solution actionAccess validation
  • 我明白了,那是一个网站项目,这种项目似乎缺少这个“条件符号”。好吧,似乎唯一的选择是将您的项目转换为 Web 应用程序。 Here a step-through
  • 哎哟......我真的很害怕这将是唯一的答案
  • 我不是这方面的专家,所以您可以等着看是否有人为您提供更好的答案

标签: c# asp.net visual-studio-2012


【解决方案1】:

https://www.codeproject.com/Questions/233650/How-to-define-Global-veriable-in-Csharp-net

在项目子目录 App_Code 中,我创建了一个 Globals.cs 文件,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GlobalVariables
{

    /// <summary>
    /// Summary description for Globals
    /// See https://www.codeproject.com/Questions/233650/How-to-define-Global-veriable-in-Csharp-net
    /// </summary>
    public static class Globals
    {
        //  Note that now the obsolete code now only leaves one warning
        //  for the block excluded code:
        //      Unreachable code detected
        //  instead of a warning line for each instance of obsolete code.
        //  The "Unreachable code detected" can be disabled and enabled with 
        //  #pragma warning disable 162 
        //  #pragma warning enable 162 
        public const bool UAT = true;

        static Globals()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }
}

在项目的.ascx.cs文件中,不需要“使用”。

在您希望它有所作为的地方,您可以这样做:

if (GlobalVariables.Globals.UAT)    //  See App_Code\Globals.cs
{
    //  Do the UAT stuff
}
else
{
    //  Do the other stuff
}

在未使用的代码中,您会收到一个警告: 警告 CS0162:检测到无法访问的代码 可以禁用此消息:

#param warning disable 162
if (GlobalVariables.Globals.UAT)    //  See App_Code\Globals.cs
{
    //  Do the UAT stuff
}
else
{
    //  Do the other stuff
}
#param warning enable 162

【讨论】:

  • 你没有理解原来的问题。我建议你删除这个答案。
最近更新 更多