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也不会再有问题。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值