2014-01-23 131 views
1

如何使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; 

} 

所以基本上如果有事情是真的,我也想返回該項目旁邊的布爾。那可能嗎?

+3

作爲示例[Dictionary.TryGetValue](http://msdn.microsoft.com/en-us/library/vstudio/bb347013(v = vs.100).aspx) – Steve

+2

我總是喜歡一個輕量級的類或結構,它提供了存儲你想要返回的值。這樣,您仍然會返回一個對象,但只要您喜歡,就可以獲得儘可能多的內容。 「出」工作,但它可以使混亂的方法。 – DonBoitnott

+2

如果可以,創建一個包含數據並賦予其語義含義的類。 「Tuple」等等都很好,但是如果你能夠讓外界知道它返回的是什麼,那麼這樣會更好。 – Arran

回答

4

基本上有兩種選擇。

第一,返回使用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) 
+2

三個選項:創建一個包含你的布爾和Item的類。 –

+1

請注意,元組在.NET 3.5中不存在。 – DonBoitnott

+0

@JonB是的,但我很明顯。 –

1

你會在一個參數使用out keyword。下面是從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; 
} 
2

一個現實世界的例子,您需要在調用中傳遞的輸出參數,出預期的參數由調用的方法進行設置。因此,例如,你可以有這樣的事情

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似乎是一個完美契合)