Skip to content

Type.GetType("xxx") 在IL中未出现过对应类型引用的情况下返回 null #773

@stuartwang

Description

@stuartwang

版本: ILRuntime 2.1.0 , unity 2022.3.34 ,

现象:
Unity 中写一个类,假设叫 Cas,并在Unity代码中引用这个类(避免被代码剥离)。 IL代码中如果不做任何对这个类的引用,只写Type.GetType("类名"),比如

            Type t2 = Type.GetType("Cas");
            if (t2==null){
                throw new Exception("t2 is null");
            }
            Debug.Log(t2.FullName);

那么查到的 t2 就会为 null。

如果在IL上下文中加上明确的 Cas 引用,比如

            Cas ss = new Cas();
            Debug.Log(ss);
或者
            Type t3 = typeof(Cas);
            Debug.Log(t3)

那么 Type t2 = Type.GetType("Cas"); 就能够查询到类型。

复现方式:
使用 Unity Demo的场景,新增一个类,在IL代码中 Type t2 = Type.GetType("Cas"); 并打印 t2就能看到查询到结果为 null。

我的理解:
Type.GetType 的执行逻辑应该是在先IL虚拟机中查询类型,之后再拿到 Assembly-CSharp 中反射查询。我猜测 ILRuntime 虚拟机提前收集了IL中用到的所有Type,提前查好并做了缓存。运行时 Type.GetType 查询一个未被 IL 使用过的类型在缓存中查不到,也没有再反射到 Assembly-CSharp 中查找。以上仅是现象和个人猜测,期待解答 。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions