简体   繁体   中英

Cannot get type by full name despite this type exists and is loaded

Weird problem, I get System.TypeLoadException "Could not load type 'Color'":

using UnityEngine;

Type.GetType(typeof(Color).FullName, true);

Of course, I cannot just use typeof(Color) , the code demonstrates that this type exists and is loaded and its name is correct.

typeof(Color).FullName == "UnityEngine.Color".

I also tried:

typeof(Color).Module.GetTypes().First(t => t.Name == "Color")

works fine, but

typeof(Color).Module.GetType("Color", true, false)

throws TypeLoadException . So I make a conclusion that it's not a "fully qualified name" problem but something else.

I also tried another types from UnityEngine assembly and from another 3rd-party assembly.

I checked Mono sources but related code is in C implementation and is quite difficult to comprehend quickly.

Type.FullName doesn't include the assembly - so unless the type is in either the calling assembly or mscorlib , it won't be found.

Basically, if you're trying to load a type from an arbitrary assembly there are two simple options:

  • Use the assembly-qualified name within Type.GetType()
  • Use Assembly.GetType

If you know another type in the same assembly at compile-time, it's often simplest to use:

Type type = typeof(KnownType).Assembly.GetType("Qualified.UnknownType");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM