Foreach для коллекции неизвестного типа - C#

Узнай цену своей работы

Формулировка задачи:

Всем добрый день. Пытаюсь обратиться поздним связыванием к библиотеке Ionic.Zip.dll. Есть работающий код:
private static void Unzip(string sourcePath, string destinationPath)
{
    ReadOptions ro = new ReadOptions();
    ro.Encoding = Encoding.GetEncoding(866); //для поддержки кириллицы в именах файлов
    using (ZipFile zip1 = ZipFile.Read(sourcePath, ro))
    {
        foreach (ZipEntry e in zip1)
            e.Extract(destinationPath, ExtractExistingFileAction.OverwriteSilently);
    }
}
Я переписал этот код, чтобы к библиотеке можно было обратиться поздним связыванием и не блокируя сам файл библиотеки (чтобы в ходе дела его можно было удалить/перезаписать):
Assembly ass = Assembly.Load(File.ReadAllBytes("Ionic.Zip.dll"));
if (ass != null)
{
    Type ReadOptions = ass.GetType("Ionic.Zip.ReadOptions");
    Type ZipFile = ass.GetType("Ionic.Zip.ZipFile");
    Type ZipEntry = ass.GetType("Ionic.Zip.ZipEntry");
    Type ExtractExistingFileAction = ass.GetType("Ionic.Zip.ExtractExistingFileAction");
    PropertyInfo ReadOptionsEncoding = ReadOptions.GetProperty("Encoding");
    MethodInfo ZipFileRead = ZipFile.GetMethod("Read", new Type[] { typeof(string), ReadOptions });
    MethodInfo ZipEntryExtract = ZipEntry.GetMethod("Extract", new Type[] { typeof(string), ExtractExistingFileAction });
    MethodInfo ZipFileDispose = ZipFile.GetMethod("Dispose");
 
    object RO = Activator.CreateInstance(ReadOptions);
    ReadOptionsEncoding.SetValue(RO, Encoding.GetEncoding(866)); //для поддержки кириллицы в именах файлов
    object ZipFileObject = ZipFileRead.Invoke(null, new object[] { @"D:\ExpSpace\Test.zip", RO });
    foreach (object ZipEntryObject in ZipFileObject)
    {
        ZipEntryExtract.Invoke(ZipEntryObject, new object[] { @"D:\ExpSpace\Test", 1 });
    }
    ZipFileDispose.Invoke(ZipFileObject, null);
}
В строке 16 ошибка. Я не могу разобраться, каким образом перечислить элементы коллекции ZipFileObject или просто получить доступ к любому из них по индексу, если тип этой коллекции неизвестен на этапе компиляции. Помогите, пожалуйста.

Решение задачи: «Foreach для коллекции неизвестного типа»

textual
Листинг программы
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
 
namespace Temp
{
   class Program
   {
      static void Main(string[] args)
      {
         Assembly ass = Assembly.Load(File.ReadAllBytes("Ionic.Zip.dll"));
         if(ass != null)
         {
            Type ReadOptions = ass.GetType("Ionic.Zip.ReadOptions");
            Type ZipFile = ass.GetType("Ionic.Zip.ZipFile");
            Type ZipEntry = ass.GetType("Ionic.Zip.ZipEntry");
            Type ExtractExistingFileAction = ass.GetType("Ionic.Zip.ExtractExistingFileAction");
            PropertyInfo ReadOptionsEncoding = ReadOptions.GetProperty("Encoding");
            MethodInfo ZipFileRead = ZipFile.GetMethod("Read", new Type[] { typeof(string), ReadOptions });
            MethodInfo ZipEntryExtract = ZipEntry.GetMethod("Extract", new Type[] { typeof(string), ExtractExistingFileAction });
            MethodInfo ZipFileDispose = ZipFile.GetMethod("Dispose");
 
            object RO = Activator.CreateInstance(ReadOptions);
            ReadOptionsEncoding.SetValue(RO, Encoding.GetEncoding(866)); //для поддержки кириллицы в именах файлов
            object ZipFileObject = ZipFileRead.Invoke(null, new object[] { @"D:\ExpSpace\Test.zip", RO });
            foreach(object ZipEntryObject in (IEnumerable)ZipFileObject)
            {
               ZipEntryExtract.Invoke(ZipEntryObject, new object[] { @"D:\ExpSpace\Test", 1 });
            }
            ZipFileDispose.Invoke(ZipFileObject, null);
         }
      }
   }
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

11   голосов , оценка 4.182 из 5
Похожие ответы