vendredi 27 janvier 2017

How to use an Interface to access classes that implemented it?

I'm trying to understand advanced use of interface. Lets say I have an inter face like bellow:

public interface IMyInterface
{

}

I have two class which implement the above interface like bellow.

public class A:IMyInterface
{
    public string AName { get; set; }
}

public class B : IMyInterface
{
    public string BName { get; set; }
}

Now I have four methods like below:

public IMyInterface CreateRawResponse()
    {
        if (condition)
        {
            return new A
            {
                AName = "A"
            };
        }
        else
        {
            return new B
            {
                BName = "B"
            };
        }
    }

    public string CreateResponse(IMyInterface myInterface)
    {
        return myInterface. // I would like to access the properties of the     parameter, since its actually a class
    }
    public string CreateResponseForA(A a)
    {
        return a.AName;
    }

    public string CreateResponseForB(B b)
    {
        return b.BName;
    }

Finally I'm trying to call the mehtods like this:

var obj = new Program();
        var KnownResponse = obj.CreateRawResponse(); // Lets say I know I will get type A
        var test1 = obj.CreateResponseForA(KnownResponse); //But I can't call like this, because CreateResponseForA() is expecting IMyInterface as parameter type.

        var UknownResponse = obj.CreateRawResponse(); // Lets say I don't know the response type, all I know is it implemented IMyInterface

        var test2 = obj.CreateResponse(UknownResponse); // I can call the method but can access the properties of the calling type in CreateResponse() mehtod.

How to handle this kind of situation? I believe there might some design pattern to solve this, but I'm not used to design patterns. Any advice would be really helpful.

Aucun commentaire:

Enregistrer un commentaire