简体   繁体   English

尽管存在并且已加载此类型,但无法通过全名获取类型

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

Weird problem, I get System.TypeLoadException "Could not load type 'Color'": 奇怪的问题,我得到System.TypeLoadException“无法加载类型'颜色'”:

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) ,代码证明此类型存在并已加载并且其名称正确。

typeof(Color).FullName == "UnityEngine.Color". 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 . 抛出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. 我还尝试了UnityEngine程序集和另一个3rd-party程序集的其他类型。

I checked Mono sources but related code is in C implementation and is quite difficult to comprehend quickly. 我检查了Mono的源代码,但是相关的代码在C实现中,很难快速理解。

Type.FullName doesn't include the assembly - so unless the type is in either the calling assembly or mscorlib , it won't be found. Type.FullName不包含程序集-因此,除非类型在调用程序集或mscorlib ,否则将找不到该类型。

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() Type.GetType()使用程序集限定名称
  • Use Assembly.GetType 使用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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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