lundi 7 janvier 2019

C# POO Cast interface parameter to concrete type

i'm trying to build a sort of framework for some base process in an app. There is some common behavior where i have to execute some operations but these operations are different depending on some scenarios. I have done something i'm not sure if it's considered a bad practice to make something like this:

    public interface IMyDto
    {
        string makerIdentifier { get; set; }
    }


    public class DtoOne:IMyDto
    {
        public string makerIdentifier { get; set; }
        //Custom properties for ConcreteOne
    }

    public class DtoTwo:IMyDto
    {
        public string makerIdentifier { get; set; }
        //Custom properties for ConcreteTwo
    }

    public abstract class AbstractMaker
    {
        public abstract void DoSomething(IMyDto myInterface);
    }

    public class ConcreteMakerOne:AbstractMaker
    {
        public override void DoSomething(IMyDto myInterface)
        {
            var concrete = myInterface as DtoOne;
            // If concrete is not null..do stuff with DtoOne properties

        }
    }

    public class ConcreteMakerTwo : AbstractMaker
    {
        public override void DoSomething(IMyDto myInterface)
        {
            var concrete = myInterface as DtoTwo;
            // If concrete is not null..do stuff with DtoTwo properties

        }
    }




    public class Customer
    {

        public void MakeSomething(IMyDto myDto)
        {
            var maker = GetMaker();
            maker.DoSomething(myDto);

        }

        private AbstractMaker GetMaker()
        {
            //Stuff to determine if return ConcreteOne or ConcreteTwo
        }
    }

The code im not happy with is the:

 var concrete = myInterface as DtoOne;

I would appreciate a lot if someone could give me some advide or tips about a pattern or good oop practice for this scenario.

Aucun commentaire:

Enregistrer un commentaire