mercredi 30 mars 2022

Create variable of class without the parameters of it's constructor

I have a BaseClass with a constructor and some parameters and then I want to do a strategy where depending of an enum, it creates one derived class or another (of that BaseClass), but with the same parameters. Is there any way to refactor this ? Thanks !

public enum GameMode
{
    ModeA,
    ModeB
}

public abstract class BaseClass
{
    public BaseClass(int a, string b, char c)
    {
        
    }
}

public class FirstGameMode : BaseClass
{
    public FirstGameMode(int a, string b, char c) : base(a, b, c)
    {
        
    }
}

public class SecondGameMode: BaseClass
{
    public SecondGameMode(int a, string b, char c) : base(a, b, c)
    {
    }
}

public class TestingPurpose
{
    private GameMode _gameMode;
    private BaseClass _baseClass;
    
    public void Init()
    {
        if (_gameMode == GameMode.ModeA)
        {
            // They use the same variables !
            _baseClass = new FirstGameMode(5, "Hello", 'c');
        }
        else
        {
            // They use the same variables !
            _baseClass = new SecondGameMode(5, "Hello", 'c');
        }
    }
}

I tried with some reflection but still I couldn't do it.

I would like to have something like

    public void Init()
    {
        BaseMatchMode type;
        if (_gameMode == GameMode.ModeA)
        {
            type = typeof(FirstGameMode);
        }
        else
        {
            type = typeof(SecondGameMode);

        }
        _baseClass = new type(5, "Hello", 'c');
    }




Aucun commentaire:

Enregistrer un commentaire