2015-11-20 5 views
0

Я пытаюсь сделать вещи проще для других разработчиков, добавив функцию ответа прямо в функцию, которую они вызывают. Я не могу объяснить, что я пытаюсь достичь здесь, но я видел это раньше, поэтому я знаю, что это возможно.вне функции, которые вне параметров

Что я хочу, чтобы результат:

InventoryController.Instance.AddItemToInventory(0, 5, out (InventoryOperations operation) => 
{ 
    switch (operation) 
    { 
     case InventoryOperations.Success: 
      Debug.Log("Successfully added the item!"); 
      break; 
     case InventoryOperations.InventoryIsFull: 
      Debug.Log("Inventory is full!"); 
      break; 
    } 
}); 

И функция они называют это:

/// <summary> 
/// Adds the item times the amount to the inventory. 
/// </summary> 
/// <param name="itemID">Item I.</param> 
/// <param name="amount">Amount.</param> 
public void AddItemToInventory(int itemID, int amount, out OnTaskComplete onTaskComplete) 
{ 
    onTaskComplete = _onTaskComplete; 

    //if we have the item, stack it 
    if(itemsInInventory.ContainsKey(itemID)) 
    { 
     //increment it 
     itemsInInventory[itemID] += amount; 
     //successfully return the operation 
     _onTaskComplete(out InventoryOperations.Success); 
    } 
    else 
    { 
     if(itemsInInventory.Count < maxInventorySpaces) 
     { 
      itemsInInventory.Add(itemID, amount); 
      _onTaskComplete(out InventoryOperations.Success); 
     } 
     else 
     { 
      _onTaskComplete(out InventoryOperations.InventoryIsFull); 
     } 
    } 
} 

Это не работает. Я просто попытался создать делегат и параметры, а также сам делегат. Но это не сработало.

+0

Но это не сработало. –

+2

Это не имеет никакого смысла. 'out' должен быть назначен где-то, и я не вижу, что это происходит где угодно. – leppie

+0

Очевидно, что вы не можете объяснить, что вы пытаетесь достичь здесь. Даже если можно, мы не поймем. –

ответ

1

Чтобы добраться туда, куда вы хотите пойти, вам действительно не нужно использовать параметр out. Просто вернуть значение из метода:

public InventoryOperations AddItemToInventory(int itemId, int amount) 

В противном случае, просто передать функцию (без ключевого слова):

InventoryController.Instance.AddItemToInventory(0, 5, (InventoryOperations operation) => 
{ 
    switch (operation) 
    { 
     // do something here 
    } 
}); 


public void AddItemToInventory(int itemID, int amount, Action<InventoryOperations> onTaskComplete) 
{ 
    var result = do some business logic here; 

    if(result == successful) 
     onTaskComplete(InventoryOperations.Success); 
    else 
     onTaskComplete(InventoryOperations.InventoryIsFull); 
} 

Либеральная psuedocode, но вы должны получить идею.

+0

благодаря ли я уже понял, но ваш так же хорош, как и ответ lee :) + 1 и проверен как ответ, спасибо за ваше время! –

0

Благодаря Ли, Все, что я должен был сделать, это использовать

System.Action

Таким образом, новый код:

InventoryController.Instance.AddItemToInventory(0, 5, (InventoryOperations operation) => 
                  { 
       switch(operation) 
       { 
       case InventoryOperations.Success: 
        Debug.Log("Successfully added the item!"); 
        break; 
       case InventoryOperations.InventoryIsFull: 
        Debug.Log("Inventory is full!"); 
        break; 
       } 
      }); 

И функция за ней:

 /// <summary> 
     /// Adds the item times the amount to the inventory. 
     /// </summary> 
     /// <param name="itemID">Item I.</param> 
     /// <param name="amount">Amount.</param> 
     public void AddItemToInventory(int itemID, int amount, Action<InventoryOperations> OnComplete) 
     { 

      //if we have the item, stack it 
      if(itemsInInventory.ContainsKey(itemID)) 
      { 
       //increment it 
       itemsInInventory[itemID] += amount; 
       //successfully return the operation 
       OnComplete(InventoryOperations.Success); 
      } 
      else 
      { 
       if(itemsInInventory.Count < maxInventorySpaces) 
       { 
        itemsInInventory.Add(itemID, amount); 
        OnComplete(InventoryOperations.Success); 
       } 
       else 
       { 
        OnComplete(InventoryOperations.InventoryIsFull); 
       } 
      } 
     }