Errors Using Generics Methods

As for my previous question , I configured my code to use Generics as

 FileHelperEngine engine; 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; } 

However, when I tried to integrate it into my code, I encountered the following two errors:

Error 1 The best overloaded method match for 'FileHelpers.FileHelperEngine <object> .WriteFile (string, System.Collections.Generic.IEnumerable <object>)' has some invalid arguments

Error 2 Argument 2: Cannot convert from 'System.Collections.Generic.List <T>' to 'System.Collections.Generic.IEnumerable <object>'

I could not understand what a mistake is. Can someone help with this.

Error line:

 engine.WriteFile(filePath, data); 

Updates1:

I use FileHelper.dll to convert Csv files, and FileHelperEngine refers to this DLL.

Updates2: As @sza suggested, I changed and follow a screenshot of my error.

enter image description here Thanks in advance.

+4
source share
3 answers

That's why. Let's take a look at the source code.

  /// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile/*'/> #if ! GENERICS public void WriteFile(string fileName, IEnumerable records) #else public void WriteFile(string fileName, IEnumerable<T> records) #endif { WriteFile(fileName, records, -1); } 

Since you are not using the generic FileHelperEngine type (generic FileHelperEngine<T> ), you can see that the method accepts the second parameter as IEnumerable , which is not a generic IEnumerable<T> , but a simple iteration over a non-generic set.

Therefore, I believe that you can do the following to make your code work:

 engine.WriteFile(filePath, (IEnumerable)data); 

or

 engine.WriteFile(filePath, data as IEnumerable); 

or

 engine.WriteFile(filePath, data.Cast<Object>()); 

Hope this helps.

+3
source

try FileHelperEngine<T> instead of FileHelperEngine

 public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> data) where T : class { FileHelperEngine<T> engine = new FileHelperEngine<T>() { HeaderText = HeaderLine }; engine.WriteFile(filePath, data); return DateTime.Now; } [FixedLengthRecord] public class Foo { } 

and using:

 ExportResultsToCsv<Foo>("", new List<Foo>()); 
+2
source

I fixed the general tags in your question, and now it becomes obvious that you are trying to call WriteFile with an invalid type. Try applying objects to objects.

 engine.WriteFile(filePath, data.Cast<Object>()); 

The problem arises because List<T> implements IEnumerable<T> rather than the IEnumerable<Object> that this method expects.

+2
source

Source: https://habr.com/ru/post/1500073/


All Articles