How to refer to an identifier without writing it into a string literal in C#?

前端 未结 5 792
甜味超标
甜味超标 2020-12-18 06:45

I often want to do this:

public void Foo(Bar arg)
{
  throw new ArgumentException(\"Argument is incompatible with \" +         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 07:18

    As has been covered, using this approach for exceptions seems unnecessary due to the method name being in the call stack on the exception.

    In relation to the other example in the question of logging the parameter value, it seems PostSharp would be a good candidate here, and probably would allow lots of new features of this kind that you're interested in.

    Have a look at this page on PostSharp which came up when I searched for how to use PostSharp to log parameter values (which it covers). An excerpt taken from that page:

    You can get a lot of useful information with an aspect, but there are three popular categories:

    • Code information: function name, class name, parameter values, etc. This can help you to reduce guessing in pinning down logic flaws or edge-case scenarios
    • Performance information: keep track of how much time a method is taking
    • Exceptions: catch select/all exceptions and log information about them

提交回复
热议问题