考虑具有以下签名的查找函数,该签名需要返回给定字符串键的整数:
int GetValue(string key) { ... }
Run Code Online (Sandbox Code Playgroud)
此外,在编写函数的源代码时,事先知道编号为N的键值映射,例如:
// N=3
{ "foo", 1 },
{ "bar", 42 },
{ "bazz", 314159 }
Run Code Online (Sandbox Code Playgroud)
因此,上述输入的函数的有效(但不完美!)实现将是:
int GetValue(string key)
{
switch (key)
{
case "foo": return 1;
case "bar": return 42;
case "bazz": return 314159;
}
// Doesn't matter what we do here, control will never come to this point
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
事先还知道每个给定密钥在运行时调用该函数的次数(C> = 1).例如:
C["foo"] = 1;
C["bar"] = 1;
C["bazz"] = 2;
Run Code Online (Sandbox Code Playgroud)
但是,此类呼叫的顺序尚不清楚.例如,上面可以描述运行时的以下调用序列:
GetValue("foo");
GetValue("bazz");
GetValue("bar");
GetValue("bazz"); …Run Code Online (Sandbox Code Playgroud)