[英]Why is my Variable Value Being Doubled Visual C#
如果這最終只是一個簡單的解決方案,請不要太討厭我,我在這里坐了好一會兒,試圖弄清楚這是怎么回事。
首先,這是我的問題:我正在向該函數傳遞CheckBox和一個常量變量。 純粹是為了讓我不必重寫8個基本相同的不同CheckBox的代碼。
無論出於什么原因,每當我嘗試在此函數中對priceOptionsTotal和totalPrice使用+ =運算符時,似乎都會將y傳遞給它的內容加倍。 例如,如果我將0.15作為y傳遞給該函數,它將顯示為0.30。
我嘗試在函數中本地執行操作,嘗試使其返回值。 我已經嘗試過在表單中生成的CheckBox函數中執行此操作。 我在某些RadioButtons中有類似的代碼,並且其中的代碼工作得很好。
這是我正在談論的功能:
private void IfChecked(CheckBox x, double y)
{
if(x.Checked == true)
{
//Add to the private global variable
pricedOptionsTotal += (decimal)y;
totalPrice += (decimal)y;
}
else if(x.Checked == false) //Check if it was just unchecked
{
//Remove Y from the totals
pricedOptionsTotal -= (decimal)y;
totalPrice -= (decimal)y;
}
if (pricedOptionsTotal > 0) //Display the pricedOptionsTotal sum in a currency format
{
displayPricedOptions.Text = "Add " + pricedOptionsTotal.ToString("C");
}
else
{
displayPricedOptions.Text = " "; //Reset textBox
}
}
這些是我的變量:
//Constant price for the base costs
private const double baseCost = 3.00; //Base cost of a burger is $3, comes with Cheddar, Swiss, or American cheese
private const double extraCheese = 0.15; //Increases the cost for more cheese.
private const double friedEgg = 0.50; //Cost of adding a Fried Egg
private const double withBacon = 0.50; //Cost of adding bacon
private const double spicyBurger = 0.75; //Cost of using special spices to make it spicy
private const double withGuacamole = 0.25; //Cost of guacamole
private const double doublePaddy = 1.00; //Cost of adding another beef paddy to the burger
//Constant price for the discount
private const double discount = 0.10; //10% discount
//Constant price for the fries
private const double sideOfFries = 3.00; //Cost of a side of fries
//Private price of priced options holder
decimal pricedOptionsTotal = 0.00m; //Price that gets displayed
//Private price of fries to use when calculating total
private decimal pricedFriesOption = 0.00m; //Fries that get displayed and added to total
//Private total price
private decimal totalPrice = (decimal)baseCost;
它開始讓我覺得我的代碼被詛咒了。
編輯:所以我現在想通了。 通過Breakpoint的功能(感謝@mjwills提醒),我發現該功能可以按預期工作。 現在的問題似乎是,一旦函數完成運行,CheckedChanges似乎又要運行一次。 意味着該功能被迫延長運行時間。
返回到CheckBox生成的CheckedChanged代碼:
在最終再次遍歷該函數並將其結論加倍我的0.15到0.30之前。 像這樣:
我不知道為什么要用這些CheckBoxes做到這一點。 該函數絕對不是它的原因,否則我將不會收到任何消息,並且該程序將陷入循環。 我對為什么這樣做感到困惑。
我在該程序中有RadioButtons,並且還有類似的代碼,並且工作正常。
謝謝@Amit和@mjwills的幫助。 由於您的幫助(並提醒您存在斷點的事實,還有@Amit,我可能會在調試時使用Call Stack,這是Visual Studio的相對較新的問題),因此我發現它在Windows中被調用了兩次。 CheckBoxes的事件。 一旦進入CheckedChanged和CheckStateChanged。 顯然,我決定將CheckBox_CheckedChanged調用放入這兩個事件中。 我真的很尷尬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.