繁体   English   中英

如何将不同类型的值分配给 if 语句中的变量,然后在 if 语句之后使用该变量?

[英]How to assign values of different types to a variable inside if statements and then use this variable after the if statements?

我正在从数据库中检索不同类型的文档,并将接收到的数据分配给变量items 不同的方法用于检索不同的文档类型,因此需要if语句。 我无法在if语句之前初始化items ,因为我事先不知道用户正在检索什么类型的文档。 问题是我因此不能在相关的īf语句执行后使用items 如何解决这个问题? 一个简化的方法:

public ActionResult ExportToExcel()
{
  ...
  if (request.docType == "docType1")
  {  
    var items = _provider.GetDocumentsOfType1(request);
  }
  else if (request.docType == "docType2")
  {
    var items = _provider.GetDocumentsOfType2(request);
  }
  else if ...

}

检索数据后,我需要根据items变量中的数据进行一些格式化,当然还需要返回数据。 似乎唯一可行的方法是用单独的方法替换 if 语句,并从那里调用格式化等方法。 但是这一切都可以在一个方法中完成吗?

您可以使用dynamic伪类型。 或者,您可以将变量声明为对象。

这两种解决方案都有缺点。

最好的解决方案是使用接口,该接口由各种可能的文档类型提供。

为了避免多个 if 语句,您可以使用 SOLID 设计原则。 所以,你可以这样做:

interface IExcelDoc
{
 ActionResult ExportToExcel();
}

public class ExcelDoc1 : IExcelDoc
{
    public ActionResult ExportToExcel()
    {
       // implementation here
    }
}

public class ExcelDoc2 : IExcelDoc
{
    public ActionResult ExportToExcel()
    {
       // implementation here
    }
}

那么你的驱动程序类可以是这样的:

public class Test 
{
    public void Main()
    {
       IExcelDoc excelDoc = GetDocType();
       excelDoc.ExportToExcel();
    }

    private IExcelDoc GetDocType()
    {
     if(...)
        return new ExcelDoc1();
     else
        return new ExcelDoc2();
    }
}

这将使您的代码在未来可维护。

看看您是否可以使用在各种文档类型之间共享的接口,或者创建这样一个接口:

public interface IDocument { }

public class Doc1 : IDocument { }

public class Doc2 : IDocument { }

如果各种DocX类具有您需要使用的共享属性或操作,那么DocX将它们添加到IDocument接口中,这将使它们无需任何类型检查和类型转换即可调用。

然后,您可以将items声明为IEnumerable<IDocument> ,并让GetDocumentsOfTypeX() -methods 都返回该类型的值:

IEnumerable<IDocument> items;

items = GetDocumentsOfType1();

public static IEnumerable<IDocument> GetDocumentsOfType1()
{
    return new List<Doc1>() { new Doc1() };
}

// (etc)

工作演示: https : //dotnetfiddle.net/Dwmmdf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM