gpt4 book ai didi

c# - 如何创建新的订阅以删除任何以前的订阅者 C# Visual Studio

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:43 25 4
gpt4 key购买 nike

我正在备考,遇到了一道我想不出来的题。它要求为 Radio 类创建一个 TurnOnRadio 方法。此方法应删除远程控制对象的任何电视订阅者。我以为我可以只用 = 而不用 += 或 -= 来做到这一点。当我这样做时说此事件“RemoteControl.channelChange ”只能位于 += 或 -= 的左侧(除非在“远程控制”类型中使用)完成此任务的任何帮助都是赞赏。代码贴在下面。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RemoteControlApp2
{
class RemoteControl
{
public delegate void ChannelChanged(object remote, RemoteEventsArgs re);
public event ChannelChanged channelChange;
private int currentChannel;

public void ChangeTheCrrentChannel(int newChannel)
{
RemoteEventsArgs newRe = new RemoteEventsArgs(newChannel);

if (channelChange!=null)
{
channelChange(this, newRe);
}
}
}

class RemoteEventsArgs : EventArgs
{
public int newChannel;

public RemoteEventsArgs(int nc)
{
this.newChannel = nc;
}
}

class Television
{
private int tvChannel;
//Your code here
public void TurnOnTV(RemoteControl Remote)
{
Remote.channelChange += new RemoteControl.ChannelChanged(TVChannelChanged);
Console.WriteLine(Remote.ToString() + " is detected");
}
public void TurnOffTV(RemoteControl Remote)
{
Remote.channelChange -= new RemoteControl.ChannelChanged(TVChannelChanged);
Console.WriteLine(Remote.ToString() + " is no longer detected");
}
public void TVChannelChanged(Object Remote, RemoteEventsArgs nc)
{
Console.WriteLine("The TV channel is changed. New channel is: {0}", nc.newChannel);
}
}

class Radio
{
private int radioChannel;
//Your code here
public void TurnOnRadio(RemoteControl Remote)
{
Remote.channelChange = new RemoteControl.ChannelChanged(TVChannelChanged);
Console.WriteLine(Remote.ToString() + " is deteceted")
}
//May need to write RadioChannelChanged method

}

class Program
{
static void Main(string[] args)
{
RemoteControl rc = new RemoteControl();
Television tv = new Television();
tv.TurnOnTV(rc);
rc.ChangeTheCrrentChannel(29);
rc.ChangeTheCrrentChannel(32);
tv.TurnOffTV(rc);
Console.ReadKey();
}
}

最佳答案

我从公共(public)事件 ChannelChanged channelchange 中取出事件;所以现在是 public ChannelChanged channelchange;接下来我完成了 radio 类和 TurnOnRadio 方法,现在该事件已被删除,我可以使用 = 删除所有其他订阅,现在订阅 Remote 在 main 中更改到的任何 channel 。下面发布 radio 类代码。

class Radio
{
private int radioChannel;
//Your code here
public void TurnOnRadio(RemoteControl Remote)
{
Remote.channelChange = new RemoteControl.ChannelChanged(RadioChannelChanged);
//Console.WriteLine(Remote.ToString() + " is deteceted");
}
public void RadioChannelChanged(object Remote,RemoteEventsArgs re)
{
radioChannel = re.newChannel;
Console.WriteLine("Radio channel is changed. New channel is :{0}", re.newChannel);
}
//May need to write RadioChannelChanged method

}

关于c# - 如何创建新的订阅以删除任何以前的订阅者 C# Visual Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com