6. Implement the Keys and values properties in the IDictionary interface
Now we can focus on the implementation of the IDictionary interface. In the 4th section, the simplest example of a particular interface is given, and let's review how it implements the keys and values attributes in the IDictionary interface.
public ICollection Keys
{ //返回所有键的集合
get
{ //把所有键的集合拷贝到新数组中并返回
Object[] keys = new Object[ItemsInUse];
for (Int32 n = 0; n < ItemsInUse; n++)
keys[n] = items[n].Key;
return keys;
}
}
public ICollection Values
{ //返回 所有值的集合
get
{ //把所有值的集合拷贝到新数组中并返回
Object[] values = new Object[ItemsInUse];
for (Int32 n = 0; n < ItemsInUse; n++)
values[n] = items [n].Value;
return values;
}
}
It is clear that it copies all the elements in the array to another memory space and returns, which once again poses a performance problem, which can be stressful if you access the keys and values properties frequently. The best solution, of course, is to refer directly to the elements in the array instead of copying them, and you want to add functionality that can be accessed using the index to access the keys returned by the ICollection property or values property. But in the 5th section of Figure 2 (preferably directly downloaded to facilitate viewing) can see the ICollection interface only a few members, and there is no Item property, how to do? It is of course to look for the right interface from the ICollection interface. As we know, the ICollection interface is the base interface for the collection interface, and its sub-interface is a more specialized collection interface, such as IDictionary representing a set of key \ value pairs, IList a collection of values that can be accessed by index.
So this time you decide to implement the public keys and values attribute separately, and return to a ilst<t> interface, and implement it manually, on the one hand to meet all the functions, on the other hand can also achieve IDictionary and Idictionary<tkey, The keys and values properties of the Tvalue> interface. Okay, let's take a look at the diagram of the Ilst<t> interface:
Figure 4 Ilist<t> Interface diagram