如何扩展接口?

时间:2015-04-16 16:46:55

标签: c# .net interface

我需要向接口添加一个新方法(MethodC),但只能为一个特定的类添加。我没有堵塞当前界面(IMyInterface),而是想为这一类使用另一个界面。这个新接口只包含一个新方法(MethodC)。但是类使用新接口也需要在IMyInterface中使用方法。

我不确定如何构建它。我从工厂方法发送回类型IMyInterface。我不知道第二个界面是如何被发回的,或者我是否可以在以后投出它。

IMyInterface
- MethodA()
- MethodB()

//new interface for single class
IMyInterfaceExtend
- MethodC()

//factory method definition
IMyInterface Factory()

IMyInterface myi = StaticClass.Factory()
myi.MethodA()
myi.MethodB()
// sometime later
// I know this doesn't work but kind of where I'm wanting to go
((IMyInterfaceExtend)myi).MethodC()

有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:2)

public interface BaseInterface
{
    string FirstName { get; set; }
    string LastName { get; set; }

    void Method1();
}

public interface ExtendedInterface
{
    string FulllName { get; set; }

    void Method2();
}

public class ClassA : BaseInterface
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public void Method1()
    { 
    }
}

public class ClassB : BaseInterface, ExtendedInterface
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName { get; set; }

    public void Method1()
    {
    }

    public void Method2()
    {
    }
}
相关问题