Do __LINE__ __FILE__ equivalents exist in C#?

前端 未结 8 2031
说谎
说谎 2020-12-01 03:53

For logging purposes

__LINE__ 
__FILE__ 

were my friends in C/C++. In Java to get that information I had to throw an exception and catch

相关标签:
8条回答
  • 2020-12-01 04:17

    Because the stack trace contains most of what you need. It will not give you the name of the file but it will give you the class/method name. It also contains the line number. It is not neglected it is automatic. You just need to throw an exception like you do it in Java

    0 讨论(0)
  • 2020-12-01 04:20

    There are already some suggestions to achieve what you want. Either use the StackTrace object or better log4net.

    In Java to get that information I had to throw an exception and catch it.

    That's not quite true. You can have it without throwing exceptions, too. Have a look to log4j. It even logs your method and class name, without polluting your code with hard coded strings containing the current method name (at least I have seen this in some occasions).

    Why are these old standbys so neglected in the modern programming languages?

    Java and C# don't make use (in the latter: excessive use) of preprocessors. And I think it's good. Abusing preprocessors to make unreadable code is very easy. And if programmers can abuse some technique ... they will abuse it.

    Just a note about performance, which is very likely to be the next thing, which pops up in your mind:

    If you use StackTrace or log4net you will always will read or hear that it is slow, because it uses Reflection. I am using log4net and I never encountered logging as a performance bottle neck. If it would be, I can declaratively deactivate (parts of) logging -- without changing the source code. That's pure beauty compared to delete all the logging lines in C/C++ code! (Besides: If performance is a primary goal, I would use C/C++ ... it will never die despite of Java and C#.)

    0 讨论(0)
提交回复
热议问题