[英]I wonder what is exact meaning of "return"
I've studying reflexive method and dictionary class(I'm nor sure it's correct in English cuz I'm Korean) and there was a example calculating fibonacci in C# book.我正在研究反身法和字典类(我不确定它在英语中是否正确,因为我是韩国人)并且在 C# 书中有一个计算斐波那契的例子。
class Fibonacci
{
private static Dictionary<int, long> memo = new Dictionary<int, long>();
public static long Get(int i)
{
if (i < 0) { return 0; }
if (i == 1) { return 1; }
if (memo.ContainsKey(i)) { return memo[i]; }
else
{
long value = Get(i - 2) + Get(i - 1);
memo[i] = value;
return value;
}
}
}
I wonder which code puts key and value into dictionary list.我想知道哪个代码将键和值放入字典列表中。 At i<0 i==0 line I think it seems "return" does that job but at
在 i<0 i==0 行我认为似乎“返回”完成了这项工作但是在
if (memo.ContainsKey(i)) { return memo[i];如果 (memo.ContainsKey(i)) { return memo[i]; }
}
here return does its job as passing(handing over?) the code if there is same key in the dictionary list.如果字典列表中有相同的键,这里返回的工作是传递(移交?)代码。 So I'm curious what does "return" actually mean.
所以我很好奇“返回”到底是什么意思。 Help!
帮助!
The i < 0
and i == 1
lines do not use the dictionary at all. i < 0
和i == 1
行根本不使用字典。 For those early terms, the dictionary lookup would be slower than the calculation anyway.对于那些早期术语,字典查找无论如何都会比计算慢。
The if (memo.ContainsKey(i)) { return memo[i]; }
if (memo.ContainsKey(i)) { return memo[i]; }
if (memo.ContainsKey(i)) { return memo[i]; }
line also does not set anything new in the dictionary. if (memo.ContainsKey(i)) { return memo[i]; }
行也没有在字典中设置任何新内容。 It reads from the dictionary, but does not write to it, because either the value is already there or we don't know what to write yet.它从字典中读取,但不写入它,因为值已经存在或者我们还不知道要写入什么。 Today, I might update this code to use
TryGetValue()
instead, in order to save one hash calculation and lookup on success.今天,我可能会更新此代码以改用
TryGetValue()
,以便在成功时节省一次 hash 计算和查找。
The line that actually writes to the dictionary is this:实际写入字典的行是这样的:
memo[i] = value;
Additionally, the reason the dictionary is named memo
is because the code uses a technique called memoization .此外,字典之所以命名为
memo
是因为代码使用了一种称为memoization的技术。
memo[i] = value;
adds value to the dictionary.为字典增加价值。 To be more precise, it adds the key value pair if the key didn't exist, or overwrites the value for the key if it existed.
更准确地说,如果键不存在,它会添加键值对,如果存在,则覆盖键的值。 Take a look:
看一看:
private static Dictionary<int, long> memo = new Dictionary<int, long>();
public static void AddToDictionary(int key, long value)
{
memo[key] = value;
foreach (var item in memo)
{
System.Console.WriteLine($"{item.Key}: {item.Value}");
}
}
Result:结果:
Adding 1,2 key-value pair.
1: 2
Adding 1,8 key-value pair.
1: 8
Adding 2,2 key-value pair.
1: 8
2: 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.