考虑以下接口:
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, ISwitch, IComponent { }
Run Code Online (Sandbox Code Playgroud)
我在类这样的类中实现了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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在这个类中实现IHeatingElement接口.IHeatingElement与IPowerSwitch具有相同的方法.那么我如何实现IHeatingElement的SwitchOn和SwitchOff.如果我尝试实现类似IPowerSwitch.SwitchOff()的东西,我会收到错误
显式接口声明中的"IPowerSwitch.SwitchOff"不是接口的成员.
我想要做的是,当电源开关事件被提升时,应该在此之后引发加热开启事件.当加热关闭时,应该提高电源开关关闭事件.
这是我的第一个问题,如果问题出现问题,请指导我.感谢您的帮助.
正如@ Peter-ritchie在评论中所说,"并非所有事情都需要通过继承来实现".在您当前的代码中,您试图说a Kettle 是一种电源开关和加热元件.我想你想说的是,Kettle 有两个电源开关和加热元件.这称为组合.
相反,你要构造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 {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
442 次 |
| 最近记录: |