对于学校的作业,我必须在 C# 中创建一个 LinkedHashTable。老师给了我一个 Table 接口,我必须通过,但是我有点迷茫,我是否在 LinkedHashTable 类中创建一个 HashTable/Dictionary,就好像它是一个数据成员并做任何管理一样把它联系起来。我最初所做的是制作:
Dictionary<Key, List<Value>> hash;
在我创建的 LinkedHashTable 类中,我实现的 get、put 和 contains 方法与该结构有关。这是表格界面:
interface Table<Key, Value> : IEnumerable<Key>
{
/// <summary>
/// Add a new entry in the hash table. If an entry with the
/// given key already exists, it is replaced without error.
/// put() always succeeds.
/// (Details left to implementing classes.)
/// </summary>
/// <param name="k">the key for the new or existing entry</param>
/// <param name="v">the (new) value for the key</param>
void Put(Key k, Value v);
/// <summary>
/// Does an entry with the given key exist?
/// </summary>
/// <param name="k">the key being sought</param>
/// <returns>true iff the key exists in the table</returns>
bool Contains(Key k);
/// <summary>
/// Fetch the value associated with the given key.
/// </summary>
/// <param name="k">The key to be looked up in the table</param>
/// <returns>the value associated with the given key</returns>
/// <exception cref="NonExistentKey">if Contains(key) is false</exception>
Value Get(Key k);
}
在测试文件中,他有如下内容:
ht.Put("Chris", "Swiss");
try
{
foreach (String first in ht)
{
Console.WriteLine("5");
Console.WriteLine(first + " -> " + ht.Get(first));
}
整个 foreach 循环让我认为我应该以这样的方式实现我的类,即它本身就是一个 LinkedHashTable,而不仅仅是某个具有 HashTable 作为成员的类。不幸的是,我很困惑如何做到这一点。任何建议都会很好。