[英]Implement Dictionary in c#
I was asked in an interview to implement the dictionary.How to implement it?I have tried implementing it using index as key using array.But Was unable to implement generic dictionary.我在一次采访中被问到实现字典。如何实现它?我尝试使用索引作为键使用数组来实现它。但是无法实现通用字典。
There are many ways to implement a class like Dictionary<T1, T2>
.有很多方法可以实现 class ,例如Dictionary<T1, T2>
。
I will describe a simple one.我将描述一个简单的。
where T1: IEquatable<T1>
is required. [编辑] 我们将比较变量 T1 的值,以便限制, where T1: IEquatable<T1>
是必需的。class MyDictionary<T1, T2> where T1 : IEquatable<T1>
{
private List<(T1 key, T2 val)> m_internal_data;
}
Equals
function. [编辑] 使用Equals
function。 Using ==
causes an error.使用==
会导致错误。public T2 Find(T1 key)
{
// Looking for a content.
foreach (var content in m_internal_data)
{
if (content.key.Equals(key))
{
return content.val;
}
}
// It reaches here when there is no content which has the same key.
// Then, I recommend to throw an exception or return a default value of T2.
return default(T2);
}
Equals
too. [编辑] 也使用Equals
。public void Store(T1 key, T2 val)
{
// Looking for a content. If exists, store a new value.
for (int i = 0; i < m_internal_data.Count; i++)
{
if (m_internal_data[i].key.Equals(key))
{
var content = m_internal_data[i];
content.val = val;
m_internal_data[i] = content;
return;
}
}
// Create a new key.
m_internal_data.Add((key, val));
}
public T2 this[T1 key]
{
get => Find(key);
set
{
Store(key, value);
}
}
That's it.而已。
Of course, this is not highly-optimized and has few useful functions.当然,这不是高度优化的,并且几乎没有有用的功能。 If you want to know how to write Dictionary more useful, I recommend you to read GitHub dotnet/runtime Dictionary.cs , which is included in .NET Core.如果您想知道如何编写更有用的 Dictionary,我建议您阅读GitHub dotnet/runtime Dictionary.cs ,它包含在 .NET Core 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.