简体   繁体   English

返回默认值。 (C#)

[英]Returning a default value. (C#)

I'm creating my own dictionary and I am having trouble implementing the TryGetValue function. 我正在创建自己的字典,但我在实现TryGetValue函数时遇到了问题。 When the key isn't found, I don't have anything to assign to the out parameter, so I leave it as is. 当找不到密钥时,我没有任何东西要分配给out参数,所以我保持原样。 This results in the following error: "The out parameter 'value' must be assigned to before control leaves the current method" 这会导致以下错误:“必须在控制离开当前方法之前将out参数'value'分配给”

So, basically, I need a way to get the default value (0, false or nullptr depending on type). 所以,基本上,我需要一种方法来获取默认值(0,false或nullptr取决于类型)。 My code is similar to the following: 我的代码类似于以下内容:

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

    ....

}

You are looking for the default keyword. 您正在寻找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;
    }

    ....

}
default(T)
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;
        }
    }

....

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字节的二进制读取只返回一个值。 C# - Binary Reading of Bytes Returning only One Value. C# C#-Office API返回400“ 69 {”错误”:{”代码”:“ RequestBodyRead”,“消息”:“无法读取值&#39;0&#39;作为带引号的JSON字符串值。“}} 0” - C# - Office API returning 400 “69 {”error“:{”code“:”RequestBodyRead“,”message“:”Cannot read the value '0' as a quoted JSON string value.“}} 0 ” 数组用另一个数组值替换匹配值。 C# - Array replace matching value with another array value. C# Cloud Firestore GetSnapshotAsync 以返回一个值。 统一与C# - Cloud Firestore GetSnapshotAsync to return a value. Unity and C# '可为空的 object 必须有一个值。' 用于 LINQ c# 中的 ICollection - 'Nullable object must have a value.' for ICollection in LINQ c# C#Dictionary是否有可能返回一个完全错误的值。 - Is it possible C# Dictionary to return a completly wrong value. 始终保留当前变量值的列表。 C# - List that always holds current variables value. C# C#:使用哈希表来存储两个相同的值。 可能吗? - C# : Using hashtables to store two of the same value. Is it possible? 获取 href 属性值时 HTMLAgilityPack 中的错误。 C# - Bug in HTMLAgilityPack when getting href attribute value. C# '可为空的 object 必须有一个值。' 对于列表 LINQ c# - 'Nullable object must have a value.' for List in LINQ c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM