【问题标题】:Can I tell when Visual Studio 2012 is in Debug vs Production?我可以知道 Visual Studio 2012 何时处于调试与生产状态吗?
【发布时间】:2014-02-20 11:11:23
【问题描述】:

我有一个视图,我想在其中有条件地显示来自两个文件之一的代码:

<% 
if (System.Diagnostics.Debugger.IsAttached) {
    Response.WriteFile("~/path/to/index-A.html");
} else {
    Response.WriteFile("~/path/to/index-B.html");
} 
%>

上面的代码可以工作......但如果附加了调试器,我实际上就不那么感兴趣了。相反,我想知道开发人员是否从 Visual Studio 2012“标准”工具栏中的配置管理器下拉菜单中选择了“调试”或“生产”。

为什么?我有一个预构建步骤,它根据“ConfigurationName”有条件地编译一些 JavaScript 和 CSS。

我试图使用这样的东西:

if (System.Configuration.ConfigurationManager == "Debug") { //...

...但这不起作用(由于各种原因),而且我的 C#/ASP.NET 知识根本缺乏这方面的知识。

帮助?

【问题讨论】:

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


    【解决方案1】:

    虽然您给出的所有答案(基本上都是一样的)都是正确的,但我无法在我的视图中发布该逻辑。我看到this answer 的评论说尝试将指令添加到控制器,然后设置一些可以在我的视图中使用的 ViewData 作为条件检查。

        public ActionResult Index()
        {
            string status = "Release";
    
            #if DEBUG
                status = "Debug";
            #endif
    
            ViewData["ConfigurationStatus"] = status;
    
            return View();
        }
    

    在我看来……

    <% 
    if (ViewData["ConfigurationStatus"] == "Debug") {
        Response.WriteFile("~/path/to/index-A.html");
    } else {
        Response.WriteFile("~/path/to/index-B.html");
    } 
    %>
    

    这就像一个魅力!

    【讨论】:

      【解决方案2】:

      您可以使用 if 指令引用来区分生产与调试。

      // preprocessor_if.cs
      #define DEBUG 
      #define MYTEST
      using System;
      public class MyClass 
      {
          static void Main() 
          {
      #if (DEBUG && !MYTEST)
              Console.WriteLine("DEBUG is defined");
      #elif (!DEBUG && MYTEST)
              Console.WriteLine("MYTEST is defined");
      #elif (DEBUG && MYTEST)
              Console.WriteLine("DEBUG and MYTEST are defined");
      #else
              Console.WriteLine("DEBUG and MYTEST are not defined");
      #endif
          }
      }
      

      【讨论】:

        【解决方案3】:
        bool isInDebug = false;
        
        #if DEBUG
            isInDebug = true;
        #endif
        

        【讨论】:

          【解决方案4】:

          使用#if directive 参考来完成您正在寻找的内容。

          #define DEBUG
          // ...
          #if DEBUG
              Console.WriteLine("Debug version");
          #endif
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-11-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-04
            • 2013-09-08
            • 1970-01-01
            相关资源
            最近更新 更多