Is there compile-time access to line numbers in C#?

后端 未结 4 2146
日久生厌
日久生厌 2021-02-12 22:39

I\'m writing a C# program using Visual Studio 2010 where I want to write out certain events to a log file and include the line number the code was on when that happened.

4条回答
  •  时光取名叫无心
    2021-02-12 23:35

    No, C# doesn't have a macro preprocessor or any meta programming features, so there are no "Compile time" solutions in the entire language. But there are 3rd party macro languages out there that you can use, if you have to, but of course it complicates the build process, Visual Studio won't just figure out how to built it by itself.

    You can even use the C preprocessor if you want it. (assuming MSVC compiler)

    cl.exe /TC /P /C /EP something.cs > something.raw.cs
    
    • cl.exe is the C compiler
    • /TC tells the C compiler to treat all files as C sources despite their extensions
    • /P tells the C compiler to only preprocess the file do not compile it
    • /C preserves the comments
    • /EP prevents the compiler from generating #line directives, that the C# compiler wouldn't understand

    This will allow you to use #include, #define and #if as well as __FILE__ and __LINE__ in your C# program, but again you have to set up Visual Studio to do this additional compilation step, or use a different build system.

提交回复
热议问题