外部加载程序集类型的反序列化

本文关键字:反序列化 类型 程序集 加载 外部 | 更新日期: 2023-09-27 18:08:09

我使用

加载外部库
Assembly assembly = Assembly.LoadFile(assemblyPath);
foreach (Type assemblyType in assembly.GetTypes())
{
    if (assemblyType.IsSubclassOf(typeof(Chip.Chip)))
    {
        Chip.Chip chip = (Chip.Chip)Activator.CreateInstance(assemblyType);
        this[chip.Name] = new ChipAssembly()
        {
            Name = chip.Name,
            Description = chip.Description,
            Image = chip.Image,
            Type = assemblyType
        };
    }
}

很好。ChipAssembly是一个助手,它拥有必要的字段+类型,它可以帮助我创建它的实例,一旦用户显式地要求它。

现在,我使用二进制序列化将其保存到一个文件中,包括类型。当我反序列化时,它抛出SerializationException,说没有找到AssemblyNamespace.AssemblyClass。但是,当我在序列化时强制类型为AssemblyClass时,它会正确地反序列化。我觉得我不知何故分配了错误的汇编类型,是吗?:)

AssemblyNamespace.AssemblyClass只是一个加载程序集的例子。

外部加载程序集类型的反序列化

如果该程序集没有静态链接到正在执行的程序集,那么在尝试反序列化之前,您需要将包含此类型的程序集加载到CLR中:

Assembly assembly = Assembly.LoadFile(assemblyPath);
// the assembly containing the type is now loaded into the CLR
// => deserialize now