Could not execute the method because the containing type is not fully instantiated

标题不够写,前面还有Exception的类型 `InvalidOperationException`.

这个错误很少见,以至于在百度上搜不到。

先说说这个异常是什么场景下出现的。

例如:

public static class SG<T>
{
    private static T _data;

    public static void Print()
    {
        Debug.Log($"data:{_data.ToString()}");
    }
}

测试代码:

private static class TestInEditor
{
    ...

    [MenuItem("TestReflection")]
    private static void TestReflection()
    {
        var type = Type.GetType("SG`1");
        Debug.Log(type);
        var method = type.GetMethod("Print", BindingFlags.Static | BindingFlags.Public);
        var action =  method.CreateDelegateT(typeof(Action)) as Action;
        Debug.Log(action);
        action.Invoke();
    }
}

此时调用即报出这个异常。

如果没有转换为Action,则报出的异常为 `InvalidOperationException: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.`

当反射一个泛型类的某个方法时,如果没有为其设置泛型类型,才会导致出错。

修复上述问题的解决方法为,在执行反射获取type后,需要将type转为泛型类

代码如下:

   [MenuItem("TestReflection")]
    private static void TestReflection()
    {
        //var type = typeof(SGData<>);
        var type = Type.GetType("SG`1");
        var genericType = type.MakeGenericType(typeof(int));
        Debug.Log(genericType);
        var method = genericType.GetMethod("Print", BindingFlags.Static | BindingFlags.Public);
        method.Invoke(null, null);
    }

此时调用则不再出现问题,且后续转换为Action也不会再有问题。

此问题主要涉及到反射,需要注意泛型类反射时一定要保证调用其方法时,已经为方法或泛型类转换了指定的类型。

猜你喜欢

转载自blog.csdn.net/DoyoFish/article/details/128274982