C#,入门教程(31)——预处理指令的基础知识与使用方法

上一篇:

C#,入门教程(30)------扎好程序的笼子,错误处理 try catchhttps://blog.csdn.net/beijinghorn/article/details/124182386

Visual Studio、C#编译器以及C#语法所支持的预处理指令,绝对是天才设计。

编译程序的时候会发现,程序可以编译成 bebug 和 release 模式,分别保存于相应的文件夹。

编写工业软件,一定有下面两个必然的需求。

一、程序的调试版本与正式版本

有些代码,仅用于调试(debug)版本,比如一些中间结果、调试信息的输出;

在正式(release )版本中,这些代码不应该被编译。

仅仅出现于 调试版本的代码,可以用户 #if DEBUG #endif 包括起来。

cs 复制代码
#if DEBUG

    Log.Write("DEBUG LINE 001");

#endif

同理,仅仅出现于正式版本的代码:

cs 复制代码
#if RELEASE

    File.Write("result.dat", dataBuffer, Encoding.UTF8);

#endif

二、不同版本程序的简约管理

工业软件的每一"段"代码,都属于"千锤百炼",会有多个版本。

保存不同的版本,可以通过版本控制、文件控制等等很多方式。

但其中最有效与直接,程序员乐于接受的却是用"预处理指令"。

计算两点之间的距离,第一个版本:

cs 复制代码
public int Distance(int ax, int ay, int bx, int by)
{
    return (int)Math.Sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by));
}

这个版本,显然有问题,可以改进:

cs 复制代码
#if _VERSION_01_
public int Distance(int ax, int ay, int bx, int by)
{
    return (int)Math.Sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by));
}
#endif

public int Distance(int ax, int ay, int bx, int by)
{
    int dx = ax - bx;
    int dy = ay - by;
    return (int)Math.Sqrt(dx * dx + dy * dy);
}

注意,这里并没有删除就的代码,而是用一个未定义名称的预处理语句包括起来了。

第一个算法的代码,不会被编译。

继续改进:

cs 复制代码
#if _VERSION_01_
public int Distance(int ax, int ay, int bx, int by)
{
    return (int)Math.Sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by));
}
#endif

#if _VERSION_02_
public int Distance(int ax, int ay, int bx, int by)
{
    int dx = ax - bx;
    int dy = ay - by;
    return (int)Math.Sqrt(dx * dx + dy * dy);
}
#endif

public int Distance(int ax, int ay, int bx, int by)
{
    int dx = ax - bx;
    int dy = ay - by;
    int dd = dx * dx + dy * dy;
    if(dd == 0) return 0;
    return (int)Math.Sqrt(dd);
}

POWER BY TRUFFER.CN

下一篇:

C#,入门教程(32)------程序运行时的调试技巧与逻辑错误探针技术与源代码https://blog.csdn.net/beijinghorn/article/details/126014885

相关推荐
RobinDevNotes9 小时前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
阿松爱学习11 小时前
【Unity开发】监听Scene场景事件
unity·c#
天天代码码天天20 小时前
屏幕翻拍满是彩色条纹?用 C# + Vulkan 做了一个去摩尔纹工具,支持单图与文件夹批量
c#·去摩尔纹
2501_9307077820 小时前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
淡海水1 天前
03-03-架构篇-SGen GC架构解析
unity·架构·c#·gc·sgen
goehou1 天前
语义缓存实战:相似度阈值、错答风险与命中率对账
ai·llm·教程·成本优化·语义缓存
曹牧2 天前
C#:输入的字符串格式不正确
c#
根号五2 天前
JetBrains Rider 使用教程(1)新建解决方案
c#·jetbrains rider
海天鹰2 天前
C#:接收从打开方式打开的参数
c#
宝桥南山2 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore