Forcing named arguments in C#

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

    I'm using another method. In my setup I have 1 parameter which I always expect, then come a bunch of optional strings which I really want to be sure the user chose actively. So my first string in this list is a "trap" value, which if set, throws an error. Like this:

        public HtmlString Toolbar(DynamicEntity target = null, string dontRelyOnParameterOrder = Constants.RandomProtectionParameter, string actions = null, string contentType = null, object prefill = null)
        {
            if (!Enabled) return null;
            protectAgainstMissingParameterNames(dontRelyOnParameterOrder);
    
            var toolbar = new ItemToolbar(target, actions, contentType, prefill);
    
            return new HtmlString(toolbar.Toolbar);
        }
    
        private void protectAgainstMissingParameterNames(string criticalParameter)
        {
            if(criticalParameter != Constants.RandomProtectionParameter)
                throw new Exception("when using the toolbar command, please use named parameters - otherwise you are relying on the parameter order staying the same.");
    
        }
    

    Hope you like it :)

提交回复
热议问题