CsvHelper.CsvWriter.WriteRecords<T>(System.Collections.Generic.IEnumerable<T>)' is obsolete

StackOverflow https://stackoverflow.com/questions/22283658

  •  11-06-2023
  •  | 
  •  

質問

I have the following code using CSVHelper:

IList<User> users = _service.GetUsers();
enter code here
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
using (CsvWriter csv = new CsvWriter(writer)) {
  csv.WriteRecords(reply.Users);
}

And I get a warning saying:

'CsvHelper.CsvWriter.WriteRecords<T>(System.Collections.Generic.IEnumerable<T>)' is obsolete: 'This method is deprecated. Use WriteRecords( IEnumerable records ) instead.' 

But isn't this what I am doing with IList?

How can I remove this warning?

Thank You, Miguel

役に立ちましたか?

解決

The WriteRecords(IEnumerable) method would work on the compile time type which has assigned to the method call during compilation and not on the runtime type. Normally the two behavior's result would be the same but there are some inheritance problem with it: what will happen if you try to create csv file from a base type (say IWillBeCsv interface) but the collection which holds these instances having other properties which are described in the base interface? They would not serialized only the ones what are defined in the interface.

Checking the source code:

[Obsolete("This method is deprecated and will be removed in the next major release. Use WriteRecords( IEnumerable records ) instead.", false)]
public virtual void WriteRecords<T>(IEnumerable<T> records)
{
  this.CheckDisposed();
  this.WriteRecords((IEnumerable) records);
}

If you are calling the generic method the internal logic will tear down the collection to an absolute basic collection type to get the most strait runtime type information from the stored objects.

How to remove the message?

using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
using (CsvWriter csv = new CsvWriter(writer)) {
    csv.WriteRecords(_service.GetUsers() as IEnumerable);
}

Cast the list to IEnumerable.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top