0

我无法从 ForEach 返回,这是我的代码:

cards.ForEach(delegate(Card c){
    if (c.GetFaceValue().ToString() == card) {
        return "Your Card has been located";
    }

错误:

无法将匿名方法转换为委托类型“... .Card>”,因为块中的某些返回类型不能隐式转换为委托返回类型

以下也不起作用,因为CheckCard只能返回 void:

 cards.ForEach(CheckCard);

 public string CheckCard(Card c) {
        if (c.GetFaceValue().ToString() == card) { // card = global 
            return "Your Card has been located";
        }
    }

错误:

'string SharedGamesClasses.Hand.CheckCard(SharedGamesClasses.Card)' 的返回类型错误

4

3 回答 3

4

You're currently trying to return a message from the anonymous function and not your calling code; that won't work as the anonymous function is an Action<T>, which can't return anything.

Do you just want to see if any element in cards matches card and return the message if so?

Use .Any() instead of .ForEach():

if (cards.Any(c => c.GetFaceValue().ToString() == card))
{
    return "Your Card has been located";
}
于 2012-05-06T12:14:22.740 回答
0

Looking on the logic provided, I suppose you just gonna terminate iteration as sson as there is Card found. Use just a simple foreach for this, like for example:

string SomeFunc(IEnumerable<Card> cards) 
{
  foreach(Card in cards)
  {
     if(c.GetFaceValue().ToString() == card) {
        return "Your Card has been located";
  }
}
于 2012-05-06T12:16:30.383 回答
0

ForEach 有一个 void - 你不能返回一个值。

Action 是一个委托快捷方式

public delegate void Action<in T>(
    T obj
)

注意这里的空白。

http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx

public void ForEach(
    Action<T> action
)
于 2012-05-06T12:13:02.187 回答