我有这个民意调查类(class)
class Poll
{
public string question { get; set; }
public Timer pollTimer { get; set; }
public List<string> userVoted { get; set; }
public Dictionary<string, int> choices { get; set; }
public bool PollRunning { get; set; }
public Poll(string question,Dictionary<string,int> choices)
{
this.question = question;
this.choices = choices;
this.pollTimer = new Timer(15000);
this.PollRunning = true;
this.userVoted = new List<string>();
}
public string pollResults()
{
string temp = "";
foreach (KeyValuePair<string, int> keyValuePair in choices)
{
temp = temp + keyValuePair.Key + " " + keyValuePair.Value + ", ";
}
return string.Format("Poll Results: {0}", temp);
}
}
我在 StartPool 方法中有此代码
static Dictionary<Channel, Poll> polls = new Dictionary<Channel, Poll>();
public void startPool(Channel channel)
{
polls.Add(channel, new Poll(question, tempdict));
polls[channel].pollTimer.Elapsed += new ElapsedEventHandler(pollTimer_Elapsed);
polls[channel].pollTimer.Start();
}
当这个方法被调用时
static void pollTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//do stuff to the poll that called this.
}
我需要知道哪个 poll 对象的计时器正在调用此方法 所以我可以做 polls[channel].pollTimer.Stop();并执行 polls[channel].pollResults();
事实上,我不知道运行时哪个轮询停止并发布结果
如果这对您有帮助,我愿意发布整个解决方案。
最佳答案
您设计 Poll 类的方式的问题在于 Poll 类没有完全完成其工作。您需要其他类知道如何启动和停止轮询,这意味着一半的轮询实现在 Poll 类内部,一半的实现在 Poll 类外部。如果您要创建一个 Poll 类,请对其他人隐藏所有实现细节。
这就是我的意思。我会在投票中创建一个事件,如下所示:
public event EventHandler<ElapsedEventArgs> Elapsed;
在 Poll 的构造函数中,添加以下行:
this.pollTimer.Elapsed += pollTimer_elapsed;
pollTimer_elapsed 看起来像这样:
private void pollTimer_elapsed(object sender, ElapsedEventArgs e)
{
var han = this.Elapsed;
if (han != null)
han(this, e); // Fire the Elapsed event, passing 'this' Poll as the sender
}
在 Poll 中添加一个新的公共(public)方法来启动计时器:
public void Start()
{
this.pollTimer.Start();
}
现在你的 startPool 方法如下所示:
public void startPool(Channel channel)
{
polls.Add(channel, new Poll(question, tempdict));
polls[channel].Elapsed += poll_Elapsed;
polls[channel].Start();
}
static void poll_Elapsed(object sender, ElapsedEventArgs e)
{
//sender is now a Poll object
var poll = sender as Poll;
// Now you can do poll.pollTimer.Stop()
// Or better yet, add a Stop method to the Poll class and call poll.Stop()
}
恕我直言,这种方法稍微好一些,因为 Poll 对象向外部对象隐藏了更多的实现。从 startPool 的角度来看,Poll 类使用起来更简单,并且您也不需要 Poll 类之外的任何内容来了解计时器。
关于c# - 包含带有计时器的对象的字典。需要找出哪个对象的计时器正在调用 elapsed 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7624611/