【发布时间】:2020-01-24 21:59:30
【问题描述】:
我正在开发一个应用程序,该应用程序允许用户在英寸、英尺和码之间转换距离。我的输出有点问题。这是我的代码:
private void convertButton_Click(object sender, EventArgs e)
{
int fromDistance = 0;
int toDistance = 0;
fromDistance = int.Parse(distanceConverterTextBox.Text);
string distanceInput = fromListBox.Items.ToString();
string distanceOutput = toListBox.Items.ToString();
switch (distanceInput)
{
case "Inches":
switch (distanceOutput)
{
case "Inches":
toDistance = fromDistance;
break;
case "Feet":
toDistance = fromDistance / 12;
break;
case "Yards":
toDistance = fromDistance / (3 * 12);
break;
}
break;
case "Feet":
switch (distanceOutput)
{
case "Inches":
toDistance = fromDistance * 12;
break;
case "Feet":
toDistance = fromDistance;
break;
case "Yards":
toDistance = fromDistance / 3;
break;
}
break;
case "Yards":
switch (distanceOutput)
{
case "Inches":
toDistance = fromDistance * 3 * 12;
break;
case "Feet":
toDistance = fromDistance * 3;
break;
case "Yards":
toDistance = fromDistance;
break;
}
break;
}
convertedDistanceLabel.Text = toDistance.ToString();
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
这是应用程序的外观:
如果有帮助,我的控件名称:
- 输入
TextBox:distanceConverterTextBox - 输出
Label:convertedDistanceLabel
我什至尝试过不将ints 声明为 0,然后我尝试了一个和/或两个,无论如何输出仍然为零。不小心使用了错误的控件名称确实可能是一个简单的情况,但我现在真的不知道还能做什么,所以非常感谢您。
【问题讨论】:
-
在函数上设置断点,并单步执行(VS 中的
F10)。您可以查看变量的值。我猜当您尝试获取控件的值时,您的问题与.Items.ToString()行有关。我认为它不会返回您期望它返回的内容。此链接包含有关如何获取值的一些信息:docs.microsoft.com/en-us/dotnet/api/… -
fromListBox.Items和toListBox.Items是集合。您可能想要两者的当前SelectedItem。使用 ListBox,您通常调用string theItemText = [ListBox].GetItemText([ListBox].SelectdItem)来检索作为文本选择的项目。它还取决于您在这些 ListBox 中放置的内容...您应该在fromDistance = (...)中放置一个断点并检查您获得的值。 -
还要记住整数除以整数是整数。
3 / 12不是 0.25,因为它不是整数。它是零。如果您希望整数除以整数为双精度或小数,则以双精度或小数进行算术。 -
@LucaCremonesi:好问题;评论不是长答案的最佳位置。简短的回答是:“throw”语句应该是可测试的;应该有一种方法可以让测试用例证明该方法应该在应该抛出的时候抛出。调试断言应该不可测试。永远不应该有一种方法可以使测试用例断言。 异常告诉你调用者的错误。断言告诉你真相。 断言的目的是告诉开发人员他们认为正确的事情实际上是错误的。
-
@LucaCremonesi:例如,考虑一个对数组进行排序的方法
void Sort(int[] a)。if (a == null) throw ArgumentNullException...是可测试的;有一种方法可以调用导致异常的方法。但是假设在返回之前我们有Debug.Assert(a.Length < 2 || a[0] <= a[1]);,也就是说,要么数组有零个元素,要么它有一个元素,或者排序后的数组的第一个元素小于第二个元素。这是关于排序数组的真相。应该没有任何情况违反该断言,因此没有测试用例。
标签: c# .net winforms distance converters