简单粗暴的“Debug模式”

在项目中,通常会遇到:调试程序和程序在线上运行时程序运行的参数不一样,

例如线上运行时程序是获取线上的机器的ip,而调试程序时,我们会指定一个ip进行调试。

又或者项目要与多个系统进行数据交换,调试的时候想屏蔽掉(不执行)这些交互的代码。

这时,我们想:要是程序能知道我们是在用Visual Studio进行调试,还是用户点击的exe执行文件使用系统,

那该美好呀!这就是Debug模式!下面我用自己的方法,实现了让程序知道是用户点的exe还是vs在调试程序。

首先我建了一个wpf应用程序(windowsForm或webForm或其它应用程序都可以),wpf程序界面上只有一个TextBlock,

用来显示当前是Debug模式或是 非Debug模式。如下图:

然后选中工程-右键-添加-新建项-应用程序配置文件(app.config),如下图:

双击app.config文件,新增两个相同key值的appSetting,key值为IsDebug,value的值分别为true和false,然后注释掉其中一个,如下图:

打开wpf程序窗体的cs文件(MainWindow),添加一个bool类型的IsDebug属性,

 然后在MainWindow的构造函数里获取配置文件key值为IsDebug的value,给IsDebug属性赋值,如下图:

至此,我们就可以通过IsDebug属性来判断当前是不是Debug模式了。用VS进行调试程序时,把配置文件里的key值为IsDebug的Value设置为true,

发布程序时把配置文件里的key值为IsDebug的Value设置为false。

然后程序要判断是否是Debug模式时,只需判断IsDebug属性了。

当配置文件里的key值为IsDebug的value为true时,程序运行截图如下:

当配置文件里的key值为IsDebug的value为false时(注释为true的配置文件字符串,把为false的取消注释):

程序运行截图如下:

程序源码如下:

XAML:

<Window x:Class="IsDebug_Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock x:Name="tb"/>
    </Grid>
</Window>
View Code

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;

namespace IsDebug_Demo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool isDebug;
        /// <summary>
        /// 是否是Debug模式
        /// </summary>
        public bool IsDebug
        {
            get { return isDebug; }
            set { isDebug = value; }
        }
        
        public MainWindow()
        {
            InitializeComponent();
            //获取配置文件key值为IsDebug的value,给IsDebug属性赋值,用来判断当前是否为Debug模式
            this.IsDebug = bool.Parse(ConfigurationManager.AppSettings["IsDebug"]);
            if (IsDebug)
            {
                tb.Text = "这是Debug模式!";
                tb.Foreground = Brushes.Red;
            }
            else
            {
                tb.Text = "这不是Debug模式!";
                tb.Foreground = Brushes.Green;
            }
        }
    }
}
View Code

配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--<add key="IsDebug" value="true" />-->
    <add key="IsDebug" value="False" />
  </appSettings>
</configuration>
View Code
原文地址:https://www.cnblogs.com/527289276qq/p/4492140.html