Check inside method whether some optional argument was passed

前端 未结 10 1582
眼角桃花
眼角桃花 2020-11-30 14:00

How do I check if an optional argument was passed to a method?

public void ExampleMethod(int required, string optionalstr = \"default string\",
    int optio         


        
10条回答
  •  一生所求
    2020-11-30 14:20

    You can't check that, because method with optional parameters is a regular method with all parameters, including those which have default values. So, your method will be compiled into:

    public void ExampleMethod(int required, string optionalstr, int optionalint)
    {
    
    }
    

    Default values are inserted by compiler in the call point. If you'll write

    ExampleMethod(42);
    

    Then compiler will generate call

    ExampleMethod(42, "default string", 10);
    

    You can compare if optionalstr or optionalint has value equal to default value, but you can't really say if it was provided by compiler or by developer.

提交回复
热议问题