Check inside method whether some optional argument was passed

前端 未结 10 1574
眼角桃花
眼角桃花 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:30

    Well, arguments are always passed. Default parameter values just ensure that the user doesn't have to explicitly specify them when calling the function.

    When the compiler sees a call like this:

    ExampleMethod(1);
    

    It silently converts it to:

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

    So it's not techically possible to determine if the argument was passed at run-time. The closest you could get is:

    if (optionalstr == "default string")
       return;
    

    But this would behave identically if the user called it explicitly like this:

    ExampleMethod(1, "default string");
    

    The alternative, if you really want to have different behavior depending on whether or not a parameter is provided, is to get rid of the default parameters and use overloads instead, like this:

    public void ExampleMethod(int required)
    {
        // optionalstr and optionalint not provided
    }
    
    public void ExampleMethod(int required, string optionalstr)
    {
        // optionalint not provided
    }
    
    public void ExampleMethod(int required, string optionalstr, int optionalint)
    {
        // all parameters provided
    }
    

提交回复
热议问题