【问题标题】:C# carry old interface functions to new interfaceC#将旧接口函数携带到新接口
【发布时间】:2012-11-10 05:28:33
【问题描述】:
以前有人问过类似的问题,但我找不到这样的答案。
C#
public interface I1 { //sealed interface, cannot change
string Property1 {get; set;}
void OnEvent();
}
public class C1 : I1 {//sealed class, cannot change
public string Property1 {get; set;}
public virtual void OnEvent() {/*update property1...*/}
}
public class C2 : C1 {//my class inherits C1. Now I want I2 for my class C2
public string Property2 {get; set;}
public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}
如何获得可以传递的包含Property1 和Property2 的接口“I2”?
【问题讨论】:
标签:
c#
oop
design-patterns
【解决方案1】:
您似乎正在尝试做一些界面不适合做的事情。接口只是一个契约,当一个类实现该契约时,它承诺它将以某种方式实现它,但接口本身不关心,因为它不关心本身带有实现细节。如果你想将行为传递给孩子,你需要子类化。
但是,如果您真的想创建一个从父接口“承载功能”的接口,那肯定是受支持且很容易实现的。您需要做的就是创建一个子接口来继承您的父接口。
例子:
interface IParentInterface
{
int FirstProperty {get;set;}
void OnChange();
}
interface IChildInterface: IParentInterface
{
string SecondProperty {get;set;}
}
class InterfaceInheritanceGoodness: IChildInterface
{
public int FirstProperty { get; set; }
public string SecondProperty { get; set; }
public void OnChange()
{
throw new NotImplementedException();
}
}
而且,接口支持多重继承...玩得开心!
【解决方案2】:
public interface I2 {
string Property1 {get; set;}
string Property2 {get; set;}
}
public class C2 : C1, I2 {
public string Property2 {get; set;}
public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}
由于C2 已经从基类中实现了Property1,它将用于隐式实现I2 接口。
【解决方案3】:
显式实现呢?
public class C2 : C1, I2
{
string I2.Property1
{
get { return base.Property1; }
set { base.Property1 = value; }
}
public string Property2 {get; set;}
public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}