简体   繁体   中英

Get compiletime constants in C#

In C# you can define compile-time constants that may be checked to configure compilation

#define MY_CONST
#if MY_CONST
    ...
#else
    ...
#endif

But I can't find a way to see which constants are defined at current line. I need something like #warning DEFINED_CONSTANTS that will give me DEBUG; NET5_0 DEBUG; NET5_0

Disregarding everything else, you could just set a field

#if MY_CONST
   public static bool IsMyConst = true;
#else
   public static bool IsMyConst = false;
#endif

Add pepper and salt to taste.

After some time I've found that it is possible to show defined constants through MSBuild with

  <Target Name="ShowConstants" AfterTargets="AfterBuild">
    <Warning Text="$(DefineConstants)" />
  </Target>

which gives TRACE;DEBUG;NET;NET5_0;NETCOREAPP for net5.0 build. It doesn't show constants for given line, but at least show constants for current configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM