簡體   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