在方法之间共享变量
这可能是一个愚蠢的问题,但我将如何去与另一种方法共享变量ammount和价格?在方法之间共享变量
[Command("sellweed")]
public void sellWeed(Client sender, Client target, int ammount, int price)
{
API.sendChatMessageToPlayer(sender, "~b~You have offered " + ammount +
" Weed to " + target + "for $" + price + ", wait for him to accept.");
API.sendChatMessageToPlayer(target, "~b~" + sender + " has offered you " + ammount +
" Weed for a price of $" + price + ", type /acceptweed to buy.");
}
[Command("acceptweed")]
public void acceptWeed(Client player)
{
checkPlayerName = API.getPlayerName(player);
string checkMoney = "SELECT Wallet FROM [playerInfo] WHERE PlayerName='" +
checkPlayerName + "'";
con.Open();
SqlCommand checkMoneyCMD = new SqlCommand(checkMoney, con);
int playerMoney = Convert.ToInt32(checkMoneyCMD.ExecuteScalar());
con.Close();
if (playerMoney < price)
{
API.sendChatMessageToPlayer(player, "You don't have enough money.");
}
else
API.sendChatMessageToPlayer(player, "You received " + ammount + " of weed.");
}
您需要制造一些获得者。
ps lol ammount实际拼写量。
把它放在变量的函数中。
public int getAmmount(){
return ammount;
}
public int getPrice(){
return price;
}
然后在功能要检索的值从你会使用:
var amount = sellweed.getAmmount();
这将变量量ammount的价值是在sellweed。 getPrice也一样。
var price = sellweed.getPrice();
难道你不应该是方法名称的资本吗?命名标准和所有.. –
@JoshuaSmith他没有在代码中大写它。我只是为了匹配他所说的。 –
只要确保你执行这项业务远离警察。 如果不在托管环境中执行,可能会导致严重的违规操作异常。
这不是一个答案,应该留在评论中。另外它现在在几个州是合法的...... :) –
如何将变量值存储在静态成员中? –
正常情况下,值通过参数列表从一个方法传递到另一个方法。就像您当前正在将Client player
传递给acceptWeed
方法一样,您也可以将price
和amount
传递给该方法。
您未显示调用此方法的位置,但推测它来自某处知道price
和amount
的地方。
此外,你应该养成使用参数化查询的习惯。您正在使用的当前语法可能会让您打开SQL注入攻击。我也在回答中包含了这一点。你可以阅读更多关于它HERE。
[Command("acceptweed")]
public void acceptWeed(Client player, int amount, int price)
{
checkPlayerName = API.getPlayerName(player);
string checkMoney = "SELECT Wallet FROM [playerInfo] WHERE PlayerName = @playerName";
using (SqlConnection con = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(checkMoney, con))
{
var playerName = new SqlParameter("playerName", SqlDbType.NVarChar);
playerName.Value = API.getPlayerName(player);
command.Parameters.Add(playerName);
int playerMoney = Convert.ToInt32(checkMoneyCMD.ExecuteScalar());
}
if (playerMoney < price)
{
// It might be nice to tell the player how much money they have
API.sendChatMessageToPlayer(player, "You don't have enough money.");
}
else
{
// Do something to subtract 'price' from 'playerMoney'
// Also do something to subtract 'amount' from the seller's stash
// And do something to add 'amount' to the buyer's stash
API.sendChatMessageToPlayer(player, "You received " + amount + " of weed.");
}
}
金额只有一个'm' –
定义了价格(即acceptWeed如何访问)? –