C#C
C#6mo ago
iskander

✅ Reflection cant find the constructor of a class that matches the given arguments

Hi! so im dipping my toes into reflections and i figured i could try to make a factory function with it.

public static T SetState<T>(params object[] args) where T : BaseGameState
{
    T state;
    if(typeof(T) == typeof(BaseGameState))
    {
        state = (T)Activator.CreateInstance(typeof(T), args)!;
    }
    else
    {
        state = (T)Activator.CreateInstance(typeof(T), CurrentState.LocalPlayer, args)!;
    }

    CurrentState = state;
       

this works for the most part but it fails for this class with this constructor:
public CardSetupState(Player player, params Span<FCard?> cards) : base(player)


this is how i call the function
FCard?[] arr = new FCard?[52];
var state = GameStatics.SetState<CardSetupState>(arr);


and this is the exception i get: System.MissingMethodException: 'Constructor on type 'Caravan.Models.GameStates.CardSetupState' not found.'

Note: when calling SetState to create the CardSetupState the second branch is hit (obviously). CurrentState and LocalPlayer are both valid references
Was this page helpful?