Check inside method whether some optional argument was passed

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

    You can't, basically. The IL generated for these calls is exactly the same:

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

    The defaulting is performed at the call site, by the compiler.

    If you really want both of those calls to be valid but distinguishable, you can just use overloading:

    // optionalint removed for simplicity - you'd need four overloads rather than two
    public void ExampleMethod(int required)
    {
        ExampleMethodImpl(required, "default string", false);
    }
    
    public void ExampleMethod(int required, string optionalstr)
    {
        ExampleMethodImpl(required, optionalstr, true);
    }
    
    private void ExampleMethodImpl(int required, int optionalstr, bool optionalPassed)
    {
        // Now optionalPassed will be true when it's been passed by the caller,
        // and false when we went via the "int-only" overload
    }
    

提交回复
热议问题