简体   繁体   English

返回多个项目

[英]Returning more than one item

How can I make a bool function return something alongside the bool? 我怎样才能让布尔函数返回布尔值呢? An example would be: 一个例子是:

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;

}

So basically if something is true, I would also like to return that item alongside the bool. 所以基本上,如果某些事情是对的,我也想将那个项目与布尔一起退还。 Is that possible? 那可能吗?

Basically, two options. 基本上有两个选择。

The first, return a result using out parameter modifier ( more info on MSDN ) 首先,使用out参数修饰符返回结果( 有关MSDN的更多信息

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

or the second, return a result packed into Tuple 或者第二个,返回打包到Tuple中的结果

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

You need an out parameter passed in the call, out parameters are expected to be set by the called method. 您需要在调用中传递一个out参数,out参数应由被调用方法设置。 So, for example, you could have something like this 因此,例如,您可能会有这样的事情

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

in the calling code you could write 在调用代码中,您可以编写

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

However, I recommend to change the name of this method to something more obvious 但是,我建议将此方法的名称更改为更明显的名称
(TryGetValue seems to be a perfect fit) (TryGetValue似乎很合适)

You would use the out keyword on a parameter. 您可以在参数上使用out关键字 Here is a real world example from Dictionary<TKey,TValue> 这是来自Dictionary<TKey,TValue>的真实示例

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;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM