简体   繁体   English

如何应用泛型方法

[英]How to apply Generics methods

I'm using FileHelper.dll for converting list into csv files and it is working perfectly. 我正在使用FileHelper.dlllist转换为csv文件,并且运行良好。

Totally I'm having 9 Lists and corresponding 9 methods to handle file conversion and it will grow in future 我总共有9个列表和相应的9种方法来处理文件转换,并且它将在未来增长

Here,I have showed only 3 methods. 在这里,我只显示了3种方法。

//-----Transaction.csv
public DateTime ExportResultsToCsv(string filePath, string HeaderLine, List<RetailTransaction> retailTxnList)
   {
      engine = new FileHelperEngine(typeof(RetailTransaction)) { HeaderText = HeaderLine };
      engine.WriteFile(filePath, retailTxnList);
            return DateTime.Now;
   }

//-----ConcessionSale.csv
public DateTime ExportResultsToCsv(string filePath, string HeaderLine, List<ConcessionSale> concessionSaleList)
    {
      engine = new FileHelperEngine(typeof(ConcessionSale)) { HeaderText = HeaderLine };
      engine.WriteFile(filePath, concessionSaleList);
      return DateTime.Now;
    }

//-----MerchandiseSale.csv
public DateTime ExportResultsToCsv(string filePath, string HeaderLine, List<MerchandiseSale> merchandiseSaleList)
  {
     engine = new FileHelperEngine(typeof(MerchandiseSale)) { HeaderText = HeaderLine };
     engine.WriteFile(filePath, merchandiseSaleList);
     return DateTime.Now;
  }

While Googling, I read some concepts in Generics however I'm not able to get an idea. 在谷歌搜索时,我阅读了Generics中的一些概念,但是我无法理解。 My concern, it is possible to use Generics here. 我担心,可以在此处使用Generics Like having one generic method instead of many method like above. 就像拥有一种通用方法而不是像上面的许多方法一样。

Please shed some light on this issue. 请阐明此问题。 Is it possible to reduce the number of methods? 是否可以减少方法数量?

Thanks in advance. 提前致谢。

public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> data)   
{
    engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine };
    engine.WriteFile(filePath, data);
    return DateTime.Now;   
}

For more info on generics see this article on MSDN 有关泛型的更多信息, 请参见MSDN上的此文章。

This is a situation where you can use generics. 在这种情况下,您可以使用泛型。 You would use a type variable, usually T is used so that is why you commonly see it. 您将使用类型变量,通常使用T,这就是为什么您通常会看到它。 This variable will replace the type of your list. 此变量将替换列表的类型。 As a result, you will need to pass the list type when calling the method 如此一来,您将需要在调用方法时传递列表类型

public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> SaleList)
{
 engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine };
 engine.WriteFile(filePath, SaleList);
 return DateTime.Now;
}

and then you could simply call it like this: 然后您可以简单地这样称呼它:

ExportResultsToCsv(filePath,Header,salesList)

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

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