jeudi 14 juillet 2022

Chain of transformations based on generic types

I'm thinking about a chain, that will allow me to perform a set of transformations with data type changing from transformation to transformation. So far I've got something like this:

public abstract class TransformationStep<T, TY>
{
    public abstract TY Execute(T input);
}

public class Times2<TY> : TransformationStep<int, TY>
{
    public Times2(TransformationStep<int, TY> next)
    {
        Next = next;
    }

    public TransformationStep<int, TY> Next { get; set; }

    public override TY Execute(int input)
    {
        var res = input * 2;
        return Next.Execute(res);
    }
}

public class ToString<TY> : TransformationStep<int, TY>
{
    public ToString(TransformationStep<string, TY> next)
    {
        Next = next;
    }

    public TransformationStep<string, TY> Next { get; }

    public override TY Execute(int input)
    {
        var res = input + "!!!";
        return Next.Execute(res);
    }
}

The only problem I see is the end chain type, where I can't convert T to TY.

public class End<T, TY> : TransformationStep<T, TY>
{
    public override TY Execute(T input)
    {
        return input;
    }
}

Do you have any solution? Also what do you think about this design and do you know any good materials on stuff like that?

Aucun commentaire:

Enregistrer un commentaire