开发者

How to write a general function to create a list of Dto from an excel file?

I have a WPF-mvvm application.

I need to read an excel file..and create a list of Dto (data transfer objects).

EX: If below are two types of DTOs Class A{ // Some properties here} Class B{// Some other properties here}

On run time, I will pass the reference to an excel file...and depending upon from which window I am calling this function I need list of that particular DTO (That means -> List(A) or List(B)).

Can I use function like below (with generics)..? But How would I know what are the properties in each class at run time ?

 private static IList<T> CreateLookupList<T>(string currentFileName)
        {
            List<T> items = new List<T>();

            Workbook internalWorkBook =开发者_如何学Python Workbook.Load(currentFileName);
                //Create data table for each worksheet
                foreach (Worksheet curWorksheet in internalWorkBook.Worksheets)
            {
            }

            return items;
        }


Your suggested approach would only work if ClassA and ClassB both implemented the same interface, or both descended from the same superclass. If that were the case, you could do something like this:

public interface IWorksheetHandler
{
    void LoadFromWorksheet(Worksheet worksheet);
}

public class DtoLoader
{
     public static IList<T> CreateLookupList<T>(string currentFileName) where T:IWorksheetHandler, new()
     {
          List<T> items = new List<T>();
          Workbook internalWorkBook = Workbook.Load(currentFileName);
          foreach (Worksheet worksheet in internalWorkBook.Worksheets)
          {
              T dto = new T();
              dto.LoadFromWorksheet(worksheet );
              items.Add(dto);
          }
          return items;
      }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜