【问题标题】:Returning more than one item退回多于一件商品
【发布时间】:2014-02-14 08:38:59
【问题描述】:

如何让 bool 函数在 bool 旁边返回一些东西?一个例子是:

public bool MyBool(List<Item> a, string lookfor)
{

  foreach(Item it in a)
  {

    if(it.itemname == look for)
    {
      //Also return the item that was found!
      return true;
    }

  }
  return false;

}

所以基本上,如果某件事是真的,我也想将该项目与 bool 一起返回。这可能吗?

【问题讨论】:

  • 我总是倾向于轻量级的类或结构,它为您希望返回的值提供存储。这样,您仍然返回单个对象,但获得尽可能多的内容。 out 有效,但它会产生混乱的方法。
  • 如果可以,创建一个类来保存数据并赋予其语义含义。 Tuple's etc 很好,但如果你能让外人非常清楚了解它返回的内容,那就再好不过了。

标签: c# function boolean


【解决方案1】:

基本上,有两种选择。

首先,使用out参数修饰符(more info on MSDN)返回一个结果

public bool MyBool(List<Item> a, string lookfor, out Item result)

或者第二个,返回一个打包到Tuple的结果

public Tuple<bool, Item> MyBool(List<Item> a, string lookfor)

【讨论】:

  • 三个选项:创建一个包含你的 bool 和 Item 的类。
  • 请注意,元组在 .NET 3.5 中不存在。
  • @JonB 是的,但我猜这很明显。
  • @JonB:我想说在实践中这并不是第三种选择。 “返回一个包含两个项目的类”实际上是涵盖您的使用和元组的第二个选项(假设这只是一个包含两个项目的类)。
  • @DonBoitnott 我知道,OP 没有指定目标框架版本,所以我自动使用最后一个。
【解决方案2】:

你需要在调用中传递一个out参数,out参数应该由被调用的方法设置。所以,例如,你可以有这样的东西

public bool MyBool(List<Item> a, string lookfor, out Item found)
{
    found = a.SingleOrDefault(it => it.itemname == lookfor);
    return found != null;
}

在你可以写的调用代码中

Item it;
if(ClassInstanceWithMethod.MyBool(ListOfItems, "itemToSearchFor", out it))
    Console.WriteLine(it.itemname);

但是,我建议将此方法的名称更改为更明显的名称
(TryGetValue 似乎很合适)

【讨论】:

    【解决方案3】:

    您可以在参数上使用out keyword。这是来自Dictionary&lt;TKey,TValue&gt;的真实示例

    public bool TryGetValue(TKey key, out TValue value)
    {
        int index = this.FindEntry(key);
        if (index >= 0)
        {
            value = this.entries[index].value;
            return true;
        }
        value = default(TValue);
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多