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

前端 未结 5 802
甜味超标
甜味超标 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:26

    well, you could cheat and use something like:

    public static string CallerName([CallerMemberName]string callerName = null)
    {
        return callerName;
    }
    

    and:

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

    Here, all the work is done by the compiler (at compile-time), so if you rename the method it will immediately return the correct thing.

提交回复
热议问题