我试图通过在他们调用的函数中添加响应函数来让其他开发人员更轻松。我无法解释我在这里想要达到的目标,但我之前已经看过了,所以我知道这是可能的。
我想要的结果是什么:
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 :(得分:1)
要想到达目的地,你真的不需要使用out param。只需返回方法中的值:
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);
}
Liberal伪代码,但你应该明白这一点。
答案 1 :(得分:0)
感谢Lee,我只需要使用
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);
}
}
}