如何从 C# 哈希表中检索自定义对象?
How to retrieve custom object from c# hashtable?
我有一个 Hashtable,我试图在其中存储一个系统 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
中的对象转换为 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
我有一个 Hashtable,我试图在其中存储一个系统 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
中的对象转换为 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