mardi 19 avril 2022

How to use MakeGenericMethod with multiple parameters

I am trying to invoke a generic method using a type argument that is parsed at runtime from a string (user input). Here is my test code:

        MethodInfo method = typeof(GameManager).GetMethod(nameof(GameManager.SetPreference));
        MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { typeof(PlayerData.Preferences), typeof(bool) });
        genericMethod.Invoke(new GameManager(), new object[] { PlayerData.Preferences.WaitMode, true });

This fails with "ArgumentException: Incorrect length".

Here is the function I'm calling:

public void SetPreference<T>(PlayerData.Preferences preference, T value)
    {
        try
        {
            PlayerData.SetAttr(preference.ToString(), value);
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            return;
        }

        OnPreferenceChanged.Raise(preference);
    }

What am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire