我從控制器接收 IFormFile。我接下來要做的是對其進行處理并獲取其內容。我希望獲得 .docx、.txt 或 .pdf 檔案,并且我想要一個類來處理基于給定擴展名的任何這些檔案。我創建并讓我的班級這樣做:
{
public static class DocumentProcessor // Should it be like this?
{
public static string GetContent(IFormFile file)
{
var result = new StringBuilder();
switch (Path.GetExtension(file.FileName))
{
case ".txt":
{
using(var reader = new StreamReader(file.OpenReadStream()))
{
while (reader.Peek() >= 0)
result.AppendLine(reader.ReadLine());
}
break;
}
}
return result.ToString();
}
}
}
無論如何,我覺得這是一個非常糟糕的解決方案,因為它是靜態的。我可以使用策略模式,但是如何定義必須使用的策略背景關系?我是否應該根據 IFormFile 物件擴展創建另一個回傳 Strategy 物件的類。但我覺得這也是一個不好的解決方案我想知道解決這個問題的最佳方法是什么
uj5u.com熱心網友回復:
創建一個新界面
interface IDocumentParser {
string GetContent(IFormFile file);
}
每個決議器擴展實作一次該介面,例如:
class TextFileParser : IDocumentParser {
public string GetContent(IFormFile file) {
//your implementation code here
}
}
然后實作一個工廠:
class ParserFactory {
public static IDocumentParser GetParserForFilename(string filename) {
/*
This is the simple way. A more complex yet elegant way would be for all parsers to include a property exposing the filetypes it supports, and they are loaded through reflection or dependency injection.
*/
switch (Path.GetExtension(fileName))
{
case ".txt":
{
return new TextFileParser();
}
// add additional parsers here
}
return null;
}
}
并使用:
IDocumentParser parser = ParserFactory.GetParserForFilename(file.FileName);
string content = parser.GetContent(file);
這被稱為“控制反轉”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480453.html
上一篇:如何找到分配給變數的物件的類?
