如何扩展接口?
How to extend an Interface?
我需要向接口添加一个新方法 (MethodC),但仅针对一个特定 class。与其阻塞当前界面 (IMyInterface),不如为这个界面使用另一个界面 class。这个新接口将只包含一个新方法 (MethodC)。但是class使用新接口还需要使用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()
知道如何实现吗?
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()
{
}
}
我需要向接口添加一个新方法 (MethodC),但仅针对一个特定 class。与其阻塞当前界面 (IMyInterface),不如为这个界面使用另一个界面 class。这个新接口将只包含一个新方法 (MethodC)。但是class使用新接口还需要使用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()
知道如何实现吗?
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()
{
}
}