如何减少以下代码中的代码冗余?我正在尝试根据上传的动态附件数量构建查询。用户最多可以添加5个附件。程序需要根据输入附件的数量检查查询并构建查询。示例代码如下所示:
StringBuilder sbView5SaveQuery = new StringBuilder();
sbView5SaveQuery.Append("update Master set ");
if (FileUpload1.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc1 = @SupportDoc1");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc1 = @CanPublishDoc1");
sbView5SaveQuery.Append(" ");
}
if (FileUpload2.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc2 = @SupportDoc2");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc2 = @CanPublishDoc2");
sbView5SaveQuery.Append(" ");
}
if (FileUpload3.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc3 = @SupportDoc3");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc3 = @CanPublishDoc3");
sbView5SaveQuery.Append(" "); ;
}
if (FileUpload4.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc4 = @SupportDoc4");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc4 = @CanPublishDoc4");
sbView5SaveQuery.Append(" ");
}
if (FileUpload5.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc5 = @SupportDoc5");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc5 = @CanPublishDoc5");
sbView5SaveQuery.Append(" ");
}
sbView5SaveQuery.Append("where MasterID = @MasterID");
答案 0 :(得分:0)
在班级中创建一个方法并将值传递给它,而不是为每次上传重复代码:
public class MyClass
{
private StringBuilder sbView5SaveQuery;
private void BuildQuery(string supportDoc, string canPublishDoc)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append(supportDoc + " = @" + supportDoc);
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append(canPublishDoc + " = @" + canPublishDoc);
sbView5SaveQuery.Append(" ");
}
public string MyMethod()
{
sbView5SaveQuery = new StringBuilder();
sbView5SaveQuery.Append("update Master set ");
if (FileUpload1.HasFile)
{
BuildQuery("SupportDoc1", "CanPublishDoc1");
}
if (FileUpload2.HasFile)
{
BuildQuery("SupportDoc2", "CanPublishDoc2");
}
// and so one...
return sbView5SaveQuery.ToString();
}
}