Forcing named arguments in C#

前端 未结 5 1296
忘了有多久
忘了有多久 2021-02-05 00:49

C# 4 introduced a feature called named arguments which is especially useful in scenarios like

int RegisterUser(string nameFirst, string nameLast, string nameMidd         


        
5条回答
  •  野性不改
    2021-02-05 01:27

    It's possible to force the callers to always use named args. I wouldn't do this in most circumstances because it's rather ugly, but it depends on how badly safe method usage is needed.

    Here is the solution:

        int RegisterUser(
    #if DEBUG
          int _ = 0,
    #endif
          string nameFirst = null,
          string nameLast = null,
          string nameMiddle = null,
          string email = null) { /*...*/ }
    

    The first parameter is a dummy that shouldn't be used (and is compiled away in Release for efficiency). However, it ensures that all following parameters have to be named.

    Valid usage is any combination of the named parameters:

        RegisterUser();
        RegisterUser(nameFirst: "Joe");
        RegisterUser(nameFirst: "Joe", nameLast: "Smith");
        RegisterUser(email: "joe.smith@example.com");
    

    When attempting to use positional parameters, the code won't compile.

提交回复
热议问题