返回一个默认值。(C#)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/367378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a default value. (C#)
提问by user4891
I'm creating my own dictionary and I am having trouble implementing the TryGetValuefunction. When the key isn't found, I don't have anything to assign to the out parameter, so I leave it as is. This results in the following error: "The out parameter 'value' must be assigned to before control leaves the current method"
我正在创建自己的字典,但在实现TryGetValue函数时遇到了问题。当找不到键时,我没有任何东西可以分配给 out 参数,所以我保持原样。这会导致以下错误:“必须在控制离开当前方法之前分配输出参数‘值’”
So, basically, I need a way to get the default value (0, false or nullptr depending on type). My code is similar to the following:
所以,基本上,我需要一种方法来获取默认值(0、false 或 nullptr,具体取决于类型)。我的代码类似于以下内容:
class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
bool IDictionary<K, V>.TryGetValue (K key, out V value)
{
return false;
}
....
}
采纳答案by Jeff Yates
回答by Strelok
return default(int);
return default(bool);
return default(MyObject);
so in your case you would write:
所以在你的情况下你会写:
class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
bool IDictionary<K, V>.TryGetValue (K key, out V value)
{
... get your value ...
if (notFound) {
value = default(V);
return false;
}
}
....
}
}
回答by BCS
default(T)