考虑以下接口:
public interface IComponent { } public interface ISwitch : IComponent { bool IsOn { get; } event EventHandler SwitchedOff; event EventHandler SwitchedOn; } public interface ISwitchable : ISwitch,IComponent { void SwitchOff(); void SwitchOn(); } public interface IPowerSwitch : ISwitchable,ISwitch,IComponent { } public interface IHeatingElement : ISwitchable,IComponent { }
我在类这样的类中实现了IPowerSwitch:
public class Kettle : IPowerSwitch { event EventHandler PowerOnEvent; event EventHandler PowerOffEvent; object objectLock = new Object(); public bool IsPowerOn; public Kettle() { IPowerSwitch p = (IPowerSwitch)this; p.SwitchedOn += new EventHandler(On_PowerOn_Press); p.SwitchedOff += new EventHandler(On_PowerOff_Press); } void ISwitchable.SwitchOff() { EventHandler handler = PowerOffEvent; if (handler != null) { handler(this,new EventArgs()); } } void ISwitchable.SwitchOn() { EventHandler handler = PowerOnEvent; if (handler != null) { handler(this,new EventArgs()); } } bool ISwitch.IsOn { get { return IsPowerOn ; } } event EventHandler ISwitch.SwitchedOff { add { lock (objectLock) { PowerOffEvent += value; } } remove { lock (objectLock) { PowerOffEvent -= value; } } } event EventHandler ISwitch.SwitchedOn { add { lock (objectLock) { PowerOnEvent += value; } } remove { lock (objectLock) { PowerOnEvent -= value; } } } protected void On_PowerOn_Press(object sender,EventArgs e) { if (!((IPowerSwitch)sender).IsOn) { Console.WriteLine("Power Is ON"); ((Kettle)sender).IsPowerOn = true; ((IPowerLamp)this).SwitchOn(); } else { Console.WriteLine("Already ON"); } } protected void On_PowerOff_Press(object sender,EventArgs e) { if (((IPowerSwitch)sender).IsOn) { Console.WriteLine("Power Is OFF"); ((Kettle)sender).IsPowerOn = false; ((IPowerLamp)this).SwitchOff(); } else { Console.WriteLine("Already OFF"); } } }
现在我想在这个类中实现IHeatingElement接口. IHeatingElement与IPowerSwitch具有相同的方法.那么我如何实现IHeatingElement的SwitchOn和SwitchOff.
如果我尝试实现类似IPowerSwitch.SwitchOff()的东西,我会收到错误
‘IPowerSwitch.SwitchOff’ in explicit interface declaration is not a member of interface.
我想要做的是,当电源开关事件被提升时,应该在此之后引发加热开启事件.当加热关闭时,应该提高电源开关关闭事件.
这是我的第一个问题,如果问题出现问题,请指导我.
感谢您的帮助.
解决方法
正如@ Peter-ritchie在评论中所说,“并非所有事情都需要通过继承来实现”.在您当前的代码中,您试图说水壶是一种电源开关和加热元件.我想你想说的是,水壶有一个电源开关和一个加热元件.这称为组合.
相反,你要构建像这样的Kettle对象:
public class Kettle : ISwitchable { private IPowerSwitch Power; private IHeatingElement Heat; public Kettle() { Power = new PowerSwitch(); Heat = new HeatingElement(); } public void SwitchOn() { Power.SwitchOn(); Heat.SwitchOn(); } // And so on. } public class PowerSwitch : IPowerSwitch {} public class HeatingElement : IHeatingElement {}