【发布时间】:2020-10-19 16:53:27
【问题描述】:
我一直认为条件编译是不好的做法,除非你无法避免。又名 #ifdefhell 见https://www.cqse.eu/en/news/blog/living-in-the-ifdef-hell/
我很惊讶微软似乎在没有评论或说明应该避免的情况下鼓励这样做。见https://docs.microsoft.com/en-us/dotnet/core/tutorials/libraries#how-to-multitarget
using System;
using System.Text.RegularExpressions;
#if NET40
// This only compiles for the .NET Framework 4 targets
using System.Net;
#else
// This compiles for all other targets
using System.Net.Http;
using System.Threading.Tasks;
#endif
是否应该避免条件编译?还是完全可以使用?对我来说很明显,由于重复代码、测试困难和维护代码库的复杂性,最好避免这种情况。然而,看到 Microsoft 文档后,我对自己的断言提出了质疑。
【问题讨论】:
-
Microsoft 不断更改每个版本的 Net 的默认选项。例如安全类,他们使用最新/最好的加密模式作为默认值。因此,如果您想要向后兼容,您可能需要使用条件编译。然后,当 Microsoft 在 Net 4.0 中为 SMTP 从 Net 3.5 升级到 Net 4.0 时,您需要添加 Net 3.5 中没有的 DefaultCredentials。
标签: c# .net compilation .net-standard .net-framework-version