微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 c# 哈希表中检索自定义对象?

如何解决如何从 c# 哈希表中检索自定义对象?

我有一个哈希表,我试图在其中存储系统 Timer 对象。如何通过其键访问 Timer 并使用其方法?有没有办法将对象转换为计时器?

Hashtable example = new Hashtable();


public void test ()
{
    System.Timers.Timer newTimer = new System.Timers.Timer();
    example.Add("test",newTimer);
    example["test"].Start(); //error
}

解决方法

为什么要使用 HashTable?使用通用的 Dictionary<string,System.Timers.Timer>

Dictionary<string,System.Timers.Timer> timers = new Dictionary<string,System.Timers.Timer>();
 
public void test ()
{
    System.Timers.Timer newTimer = new System.Timers.Timer();
    timers.Add("test",newTimer);
    timers["test"].Start(); 
}

当然,您也可以简单地将 HashTable 中的 Object 强制转换为 System.Timers.Timer,但在 99% 中 HashTable 已过时。因此,对于上面的代码,您必须对其进行强制转换:

System.Timers.Timer timer = example["test"] as System.Timers.Timer;
timer?.Start(); // the ? ensures that the code works even if the type is not a Timer,it simply skips it

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。