返回一个默认值。(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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:44:19  来源:igfitidea点击:

Returning a default value. (C#)

c#genericsdefault-value

提问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

You are looking for the defaultkeyword.

您正在寻找default关键字。

For example, in the example you gave, you want something like:

例如,在你给出的例子中,你想要这样的东西:

class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
    bool IDictionary<K, V>.TryGetValue (K key, out V value)
    {
        value = default(V);
        return false;
    }

    ....

}

回答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)