Assembly.GetType()和typeof()返回不同的类型?

假设您获得了一个由以下简单代码编译的Class.dll程序集:

namespace ClassLibrary { public class Class { } } 

并考虑使用上述Class.dll作为项目引用的不同项目,并使用以下代码:

 Assembly assembly = Assembly.LoadFrom(@"Class.dll"); Type reflectedType = assembly.GetType("ClassLibrary.Class"); Type knownType = typeof(ClassLibrary.Class); Debug.Assert(reflectedType == knownType); 

断言失败了,我不明白为什么。

如果我将ClassLibrary.Class替换为System.Text.RegularExpressions.Regex类和带有System.dll的Class.dll,断言会成功,所以我猜它与项目属性有关吗? 一些编译开关或许?

提前致谢

问题是加载上下文:通过.LoadFrom加载的程序集保存在与Fusion(.Load)加载的程序集不同的“堆”中。 这些类型实际上与CLR不同。 有关CLR架构师的更多详细信息,请查看此链接 。

您可能正在加载同一组件的两个不同副本。

knownType.Assembly与调试器中的knownType.Assembly进行比较,并查看路径和版本。

我想你没有引用从磁盘加载的相同程序集。

此示例(编译为Test.exe )工作正常:

 using System; using System.Reflection; class Example { static void Main() { Assembly assembly = Assembly.LoadFrom(@"Test.exe"); Type reflectedType = assembly.GetType("Example"); Type knownType = typeof(Example); Console.WriteLine(reflectedType == knownType); } }