[英]How can I avoid duplicated code in this situation?
I built a javascript script that creates dynamic forms, and I'm creating a validation for each section that the user creates, that updates the title from the duplicated questions.我构建了一个创建动态表单的 javascript 脚本,我正在为用户创建的每个部分创建一个验证,从重复的问题更新标题。 So, I built a method for that.
所以,我为此建立了一个方法。 The user can choose between creating a section with dropboxes, checkboxes...
用户可以在创建带有保管箱、复选框的部分之间进行选择...
So, I had to create 6 methods with exacly the same code, I'm only changing the type of the list.所以,我不得不用完全相同的代码创建 6 个方法,我只是改变了列表的类型。 Is there any wait to prevent that, creating a generic method?
是否有任何等待来阻止这种情况,创建一个通用方法?
private static int CheckDuplicatedDropdownQuestions(Template template, int i, List<string> collectQuestions)
{
foreach (var field in template.Fields.Dropdown)
{
if (!collectQuestions.Contains(field.Title))
{
collectQuestions.Add(field.Title);
}
else
{
field.Title = field.Title + " (" + i + ")";
i++;
}
}
return i;
}
...
Try creating a new method for the foreach part尝试为 foreach 部分创建一个新方法
private static int CheckDuplicatedDropdownQuestions(Template template, int i,
List<string> collectQuestions,string field)
{
if(field=="Dropdown")
{
NewMethod(template.Fields.Dropdown,ref i);
}
else if(field=="CheckBox")
{
NewMethod(template.Fields.CheckBox,ref i);
}
return i;
}
private static void NewMethod(var FieldType,ref int i)
{
foreach (var field in FieldType)
{
if (!collectQuestions.Contains(field.Title))
{
collectQuestions.Add(field.Title);
}
else
{
field.Title = field.Title + " (" + i + ")";
i++;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.