'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?
Solution 1:[1]
MakeGenericMethod's parameters are for the type-parameters of the target generic method not the method parameters, in your case the SetPreference method only has 1 type-parameter: T, not 2.
For SetPreference<Boolean> pass only new Type[] { typeof(Boolean) } - so don't pass typeof(PlayerData.Preferences) to MakeGenericMethod.
MethodInfo method = typeof(GameManager).GetMethod(nameof(GameManager.SetPreference));
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { typeof(bool) });
genericMethod.Invoke(new GameManager(), new object[] { PlayerData.Preferences.WaitMode, true });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dai |
