zoukankan      html  css  js  c++  java
  • 第十六章 调试及安全性(In .net4.5) 之 调试程序

    1. 概述

      本章内容包括 如何选择合适的构建类型、创建和管理编译指令、管理程序数据文件(pdb)和指令。

    2. 主要内容

      2.1 构建类型

        .net中默认的两种生成模式是 发布(Release)模式 和 调试(Debug)模式。

      2.2 创建和管理编译指令

        ① 预编译指令:C#中的预编译指令,用于在编译过程中调整逻辑。

    public void DebugDirective() 
    { 
        #if DEBUG 
            Console.WriteLine(“Debug mode”); 
        #else 
            Console.WriteLine(“Not debug”); 
        #endif 
    }

        * DEBUG 指令是系统自带的,用户还可以使用#define来自定义预编译指令。使用自定义预编译指令会降低程序的可读性,一般不建议使用。

        预编译指令比较常见的一个应用场景是 编写一个面向多平台的类库时。

    public Assembly LoadAssembly<T>() 
    {  
        #if !WINRT 
            Assembly assembly typeof(T).Assembly; 
        #else 
            Assembly assembly typeof(T).GetTypeInfo().Assembly; 
        #endif 
     
        return assembly; 
    }

        系统自带的预编译指令还有:#undef, #warning, #error, #line, #pragma.

    #warning This code is obsolete 
     
    #if DEBUG 
    #error Debug build is not allowed 
    #endif
    #line 200 “OtherFileName” 
        int a;    // line 200 
    #line default 
        int b;   // line 4 
    #line hidden  
        int c; // hidden 
        int d; // line 7
    #pragma warning disable 0162, 0168 
    int i; 
    #pragma warning restore 0162 
    while (false) 
    { 
        Console.WriteLine(“Unreachable code”); 
    } 
    #pragma warning restore 

        想要只在调试模式执行特定的方法,除了#ifdebug之外,还可以用 ConditionalAttribute。

    [Conditional(“DEBUG”)] 
    private static void Log(string message) 
    { 
        Console.WriteLine(“message”); 
    }

         DebuggerDisplayAttribute 可用于在调试模式按指定的格式输出字符串。

    [DebuggerDisplay(“Name = {FirstName} {LastName”)] 
    public class Person 
    { 
        public string FirstName { getset; } 
        public string LastName { getset; } 
    }

      2.3 管理程序数据文件和符号

        编译程序时,可以选择创建一个程序数据文件(.pdb),这个文件中保存了一些对调试有用的附加信息。

        一个pdb文件包含两部分信息:① 源程序文件名和行号;② 本地变量名。

        * 可以使用微软提供的Microsoft Symbol Server来解决系统pdb文件缺失的问题。

        * 可以使用Team Foundation Server(TFS)来创建自己的Sympol Server,这样就可以在没有源码的情况下调试各个版本的程序。

        * 建议将每次编译好的pdb文件都保存下来。发布到公共位置时,可以使用PDBCopy工具来移除PDB文件中的私有信息。

    pdbcopy mysymbols.pdb publicsymbols.pdb –p

    3. 总结

      ① Visual Studio的构建配置功能可以用来配置编译器。

      ② 用debug模式生成的程序,是没有经过代码优化的,包含额外的调试信息。

      ③ 用release模式生成的程序,是经过代码优化的,可以发布到生产环境。

      ④ 编译指令可以给编译器提供额外的说明信息。可以用来在特定的生成模式引入代码或者发出警告。

      ⑤ 一个PDB文件包含在调试时需要用到的附加信息。

  • 相关阅读:
    高效求解素数
    搭建redis集群
    搭建Spark高可用集群
    redis持久化
    elasticsearch简介
    java反射机制
    hdfs的客户端操作
    hdfs运行机制
    大数据概念
    hive
  • 原文地址:https://www.cnblogs.com/stone_lv/p/4387509.html
Copyright © 2011-2022 走看看