2017-04-24 201 views
-1

這可能是一個愚蠢的問題,但我將如何去與另一種方法共享變量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."); 
} 
+0

金額只有一個'm' –

+1

定義了價格(即acceptWeed如何訪問)? –

回答

-1

您需要製造一些獲得者。
ps lol ammount實際拼寫量。

把它放在變量的函數中。

public int getAmmount(){ 
     return ammount; 
} 
public int getPrice(){ 
     return price; 
} 

然後在功能要檢索的值從你會使用:

var amount = sellweed.getAmmount(); 

這將變量量ammount的價值是在sellweed。 getPrice也一樣。

var price = sellweed.getPrice(); 
+0

難道你不應該是方法名稱的資本嗎?命名標準和所有.. –

+0

@JoshuaSmith他沒有在代碼中大寫它。我只是爲了匹配他所說的。 –

0

只要確保你執行這項業務遠離警察。 如果不在託管環境中執行,可能會導致嚴重的違規操作異常。

+0

這不是一個答案,應該留在評論中。另外它現在在幾個州是合法的...... :) –

+0

如何將變量值存儲在靜態成員中? –

0

正常情況下,值通過參數列表從一個方法傳遞到另一個方法。就像您當前正在將Client player傳遞給acceptWeed方法一樣,您也可以將priceamount傳遞給該方法。

您未顯示調用此方法的位置,但推測它來自某處知道priceamount的地方。

此外,你應該養成使用參數化查詢的習慣。您正在使用的當前語法可能會讓您打開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."); 
    } 
}