Forcing named arguments in C#

前端 未结 5 1315
忘了有多久
忘了有多久 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:35

    I've also sought a way to force named arguments. Optional parameters can be dangerous, especially if you have multiple parameters of the same type. Overloads are almost always a safer solution, but there are times when you have a method that can take many combination of arguments, so creating 20 overloads to account for ever possibility is overkill.

    In extreme situations where it is of the utmost importance that arguments be named at all times, I will create an argument class with no defined constructor. In your case, you could do this:

    public class UserRegistrationArguments
    {
        public string nameFirst { get; set; }
        public string nameLast { get; set; }
        public string nameMiddle { get; set; }
        public string email { get; set; }
    }
    

    Call it like this:

    RegisterUser(new UserRegistrationArguments { nameFirst = "Bob", nameLast = "Slob" });
    

    You could also simplify it like this:

    public class UserRegistrationArguments
    {
        public string nameMiddle { get; set; }
        public string email { get; set; }
    }
    
    int RegisterUser(string nameFirst, string nameLast, UserRegistrationArguments args = null)
    

    ...and do this:

    RegisterUser("Bob", "Slob", new UserRegistrationArguments { nameMiddle = "Teh" }); 
    

    This way, you only have one optional parameter and that's for your optional parameters.

    Edit: Maybe I didn't read the OP correctly. You're not using optional arguments? If not then this answer probably doesn't help you.

提交回复
热议问题