gpt4 book ai didi

c# - 无法将值传回对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:55 25 4
gpt4 key购买 nike

在我的类 PlayerInventory 中,我有一个称为买卖的方法。我在名为 statItem 的参数中有一个 int。它将用作我的对象播放器中项目的占位符。

public void Buy(PlayerStats player, string myName, int myItem, int statItem)
{
Console.WriteLine("{0} Costs {1:C} per unit.", myName, myItem);
int MaxPurchase = player.Money / myItem;
Console.WriteLine("You can afford {0} units.", MaxPurchase);
Console.WriteLine("How many units would you like to purchase?");
string Purchasex = Console.ReadLine();
int ammount = int.Parse(Purchasex);
player.Money -= (myItem * ammount);
statItem += ammount;
Console.WriteLine("You have Purchased {0} units at {1:C} per unit.", ammount, myItem);
Console.ReadLine();
}

在 BuyMerchandise/SellMerchandise 方法中,我有一个开关,我用 player.LuxuryWatches、player.LuxuryHandbags 等替换了 statItem 参数。

Console.WriteLine("What would you like to purchase? \n");
ViewInventory(player);
switch (GetChoice())
{
case "1":
Price(player);
Buy(player, "Luxury Watches", _LuxuryWatches, player.LuxuryWatches);
break;
case "2":
Price(player);
Buy(player, "Luxury Handbags", _LuxuryHandbags, player.LuxuryHandbags);
break;

这不是将值传递回播放器对象中的变量。

例如,如果我用 player.LuxuryWatch 替换 statItem,它确实会将值传回对象。但我更愿意使用参数,这样我就可以使用一种方法并更改十项中每一项的参数。

    public void Buy(PlayerStats player, string myName, int myItem)
{
Console.WriteLine("{0} Costs {1:C} per unit.", myName, myItem);
int MaxPurchase = player.Money / myItem;
Console.WriteLine("You can afford {0} units.", MaxPurchase);
Console.WriteLine("How many units would you like to purchase?");
string Purchasex = Console.ReadLine();
int ammount = int.Parse(Purchasex);
player.Money -= (myItem * ammount);
player.LuxuryWatches += ammount;
Console.WriteLine("You have Purchased {0} units at {1:C} per unit.", ammount, myItem);
Console.ReadLine();
}

最佳答案

因为 int 是一个值类型,statItem 只是作为参数传递给 Buy 方法的值的副本。

原始解决方案

需要对当前设计进行最少更改的解决方案是使用 ref关键词如:

public void Buy(PlayerStats player, string myName, int myItem, ref int statItem)
{
// your code here
}

然后这样调用它:

int amount = player.LuxuryWatches;
Buy(player, "Luxury Watches", _LuxuryWatches, ref amount);
player.LuxuryWatches = amount;

还有其他更清洁、更灵活和可维护的替代方案,但需要对整体设计进行更多更改。

关于c# - 无法将值传回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com