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

The title is not enough, and there is an Exception type `InvalidOperationException` in front of it.

This error is so rare that it cannot be found on Baidu.

Let me first talk about the scenario where this exception occurs.

For example:

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

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

Test code:

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();
    }
}

At this time, the call will report this exception.

If it is not converted to Action, the exception reported is `InvalidOperationException: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.`

When reflecting a method of a generic class, if the generic type is not set for it, it will cause an error.

The solution to fix the above problem is to convert the type to a generic class after performing reflection to obtain the type

code show as below:

   [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);
    }

At this time, there will be no problem with the call, and there will be no problem with the subsequent conversion to Action.

This problem is mainly related to reflection. It is necessary to pay attention to the generic class reflection to ensure that the specified type has been converted for the method or generic class when calling its method.

Guess you like

Origin blog.csdn.net/DoyoFish/article/details/128274982