如何使用接口访问实现它的类?

时间:2017-01-27 13:21:48

标签: c# oop design-patterns interface polymorphism

更新:我的初步计划是将其用于向上转发和向下转发。我只是希望我的方法能够根据服务器的不同响应返回不同的类。

我正在尝试了解界面的高级用法。可以说我有一个像bellow那样的界面:

public interface IMyInterface
{

}

我有两个类实现上面的接口,如bellow。

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

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

现在我有四种方法,如下所示:

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;
}

最后,我试图调用这样的方法:

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.

如何处理这种情况?我相信可能有一些设计模式可以解决这个问题,但我不习惯设计模式。任何建议都会非常有用。

1 个答案:

答案 0 :(得分:2)

接口应该具有与实现它的所有人共同的成员

public interface IMyInterface {
    string Name { get; set; }
}

因此

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

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

这意味着你的情况就变了。

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

public string CreateResponse(IMyInterface myInterface)
{
    return myInterface.Name;
}
public string CreateResponseForA(A a)
{
    return a.Name;
}

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

然后也可以重构为

public string CreateResponse(IMyInterface myInterface)
{
    return myInterface.Name;
}
public string CreateResponseForA(A a)
{
    return CreateResponse(a);
}

public string CreateResponseForB(B b)
{
    return CreateResponse(b);
}