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

后端 未结 4 2144
日久生厌
日久生厌 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:36

    CAVEATS: This is NOT an answer to the OP. I know that. But people looking for something similar may find this page.

    • This is not about .NET 4.
    • This is still ultimately a run-time solution.

    But VS 2015, C#, .NET Core or .NET 4.5 allow:

    using System.Runtime.CompilerServices;
    using System.Diagnostics;
    
    public static String CurrentLocation(
      [CallerFilePath] string file = null,
      [CallerLineNumber] int lineNumber = 0,
      [CallerMemberName] string method = null)
    {
      String location = file;
      if (lineNumber != 0)
      {
        location += "(" + lineNumber.ToString() + ")";
      }
      if (!String.IsNullOrWhiteSpace(method))
      {
        location += ": " + method;
      }
      if (!String.IsNullOrWhiteSpace(location))
      {
        location += ": ";
      }
      return location;
    }
    

    [UPDATED USAGE]

    With usage something like:

    Console.Error.WriteLine(CurrentLocation() + "some message");
    

    or

    Debug.WriteLine(CurrentLocation() + "some message");
    

提交回复
热议问题