【问题标题】:how to return ValueKeyPair or something else if pair wasn't found?如果找不到对,如何返回 ValueKeyPair 或其他东西?
【发布时间】:2014-04-13 13:33:42
【问题描述】:

我有一个由 Vehicle(key) 和 Owner(value) 构建的字典。 我有一种方法可以通过给定车辆的许可证号搜索 ValueKeyPair,如果找到它, 它返回找到的许可证的 valueKeyPair。

但是如果在搜索过程中该方法没有找到匹配的 Key,那么它应该返回什么? 似乎 ValueKeyPair 不能初始化为 NULL,所以我不能返回 null。

你能告诉我该怎么做吗? 谢谢。

【问题讨论】:

  • 能否请您发布特别给您带来麻烦的代码。

标签: c# visual-studio-2012 dictionary key-value


【解决方案1】:

假设KeyValue都是String类型,你可以像这样返回KeyValuePair<string, string>的默认值:

return default(KeyValuePair<string, string>);

和你正在检查的代码,你可以检查键的空值。

修改您的方法以返回 nullable KeyValuePair,这使您能够返回 null。 将返回类型从 KeyValuePair&lt;string, string&gt; 替换为 KeyValuePair&lt;string, string&gt;?

private KeyValuePair<string, string>? MethodName()
{   
    return null;
}

【讨论】:

    【解决方案2】:

    为什么不在 if 语句中使用 TryGetValue?

    http://msdn.microsoft.com/en-us/library/bb347013(v=vs.110).aspx
    

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      相关资源
      最近更新 更多