【问题标题】:How to retrieve custom object from c# hashtable?如何从 C# 哈希表中检索自定义对象?
【发布时间】:2021-07-26 01:40:17
【问题描述】:

我有一个哈希表,我试图在其中存储一个系统 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
}

【问题讨论】:

    标签: c# timer hashtable


    【解决方案1】:

    你为什么要使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多