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

时间:2011-09-07 20:45:16

标签: c# dll .net-assembly

我使用

加载外部库
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是一个帮助器,它包含必要的字段+ Type,帮助我在用户明确要求时创建它的实例。

现在,我使用二进制序列化将其保存到文件中,包括类型。当我反序列化时抛出SerializationException,说没有找到AssemblyNamespace.AssemblyClass。但是,当我在序列化时强制键入AssemblyClass时,它会正确地反序列化。我觉得我以某种方式分配错误的assemblyType,是吗? :)

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

1 个答案:

答案 0 :(得分:1)

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

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