Assembly.GetType() and typeof() return different t

2019-05-09 14:26发布

Suppose you are given a Class.dll assembly compiled from the following simple code:

namespace ClassLibrary
{
    public class Class
    {
    }
}

And consider a different project with the above Class.dll as a project reference and with the following code:

Assembly assembly = Assembly.LoadFrom(@"Class.dll");

Type reflectedType = assembly.GetType("ClassLibrary.Class");
Type knownType = typeof(ClassLibrary.Class);

Debug.Assert(reflectedType == knownType);

The assertion fails, and I don't understand why.

The assertion succeeds if I replace the ClassLibrary.Class with, say, the System.Text.RegularExpressions.Regex class and Class.dll with System.dll, so I'm guessing it has something to do with the project properties ? some Compilation switch perhaps?

Thanks in advance

3条回答
The star\"
2楼-- · 2019-05-09 14:27

I would imagine that you are not referencing the same assembly that you are loading from disk.

This example (when compiled as Test.exe) works just fine:

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);
    }
}
查看更多
在下西门庆
3楼-- · 2019-05-09 14:43

The problem is load contexts: assemblies loaded via .LoadFrom are kept in a different "pile" than those loaded by Fusion (.Load). The types are actually different to the CLR. Check this link for more detail from a CLR architect.

查看更多
祖国的老花朵
4楼-- · 2019-05-09 14:45

You're probably loading two different copies of the same assembly.

Compare knownType.Assembly to reflectedType.Assembly in the debugger, and look at the paths and versions.

查看更多
登录 后发表回答