我将要创建日期和字符串变量,这些变量需要能够按时间排序。在脚本运行时,此信息收集将需要添加和删除条目。根据我的研究,似乎可行的方法是创建一个哈希表,该哈希表使用该键创建一个具有特定日期时间值的时间,该时间值具有一个关联的自定义类,该类具有DateTime和String信息的属性。这将允许我按键对哈希进行排序,并且可以根据需要在哈希表中添加和删除项目。我创建的自定义类是下面的执行器。
public class Executor {
public DateTime StartTime { get; set; }
public string Name { get; set; }
public string Executable { get; set; }
public Executor(DateTime starttime, string name, string executable) {
StartTime = starttime;
Name = name;
Executable = executable;
}
}
使用此类,我可以创建一个循环,以创建while循环所允许的各种实例并将其添加到哈希表中。下面的代码创建需要存储在哈希表中的信息,并接受一个列表,该列表提供了生成哈希的规则的输入。为了简单起见,以下示例中删除了一些定义时间和遍历列表的代码。
static void CreateScriptScehdule(List<Script> scriptList) {
// Declare and initialize variables
Hashtable htExecutionList = new Hashtable();
// Code to create a list of the times and manage the item properties
...
...
// Create a loop to define the exeuction times of the script between the start and stop time.
// use a tempTime to compare to the stop time
while (DateTime.Compare(tempTime,timeStop) < 0) {
// Create an object for the executable based on the script rules
Executor exe = new Executor(tempTime,item.Name,item.Executable);
// Add the executable object to the hashtable htExecutionList
double exeTimeEpoch = ttoe(tempTime);
exeKey = exeTimeEpoch.ToString() + item.Name;
htExecutionList.Add(exeKey,exe);
}
// Loop through the hashtable to print out the stored information to verify the creation for debugging
foreach (DictionaryEntry s in htExecutionList) {
//Console.WriteLine(s.Value);
}
}
当我检查s.Value的值时,我收到了值ReceiveConfigFile.Executor。这使我相信可以从ReceiveConfigFile脚本存储对象Executor,但是当我尝试检索诸如 StartTime 或 Name 之类的属性时,会收到错误消息。我一直试图将值打印为 s.Value.Name ,以为我可以获取对象属性。我收到的错误是:
error CS1061: 'System.Collection.DictionaryEntry' does not contain a definition for 'Namel accepting a first argument of type 'System.Collections.DictionaryEntry' could be found (are you missing a using directive or an assembly reference)
答案 0 :(得分:-1)
我能够通过使用字符串作为键和值的自定义类的对象来实现我的目标。引起我入门上麻烦的一项是我需要加载System.Collections.Generic。
using System.Collections.Generic;
首先,我以Executor类作为值将字典初始化为字符串键开始。
Dictionary<string, Executor> ExecutionDict = new Dictionary<string, Executor>();
接下来,我需要将键定义为唯一的值,因此我创建了一个与特定时间和描述相关联的变量,以知道即使关联了时间,该键也永远不会重复。 exe变量存储了Executor类的实例,该实例具有代码中先前定义的变量。最后一行将条目添加到字典中。我将此代码循环了起来,因此每次都能继续添加相同的变量和新值。
While (condition) {
Executor exe = new Executor(tempTime,item.Name,item.Executable);
exeKey = exeTimeEpoch.ToString() + item.Name;
ExecutionDict.Add(exeKey,exe);
}
最后,我在字典中创建了一个循环以查找所有实例,并打印出值以测试变量的创建。
foreach(KeyValuePair<string,Executor> temp in ExecutionDict) {
Console.WriteLine("For the Key {0} the Name is {1} and the Name is {2} and the Name is {3}", temp.Key, temp.Value.Name, temp.Value.Executable, temp.Value.StartTime);
}