【问题标题】:C# for loops text compareC# for 循环文本比较
【发布时间】:2016-03-25 17:33:33
【问题描述】:

我试图通过遍历值并找到与我的直径变量匹配的值来分配组合框索引。 (组合框项会根据直径而变化,例如,某些管道类型只有 0.5"、1.0" 而其他可能具有中间 0.75" 值)。

代码比较似乎永远不会成立(因此 myIndex 从未在初始化之外分配任何内容),尽管当我在其上放置断点时,文本字符串会在适当的迭代中匹配。

int myIndex = 0;

for (int i = 0; i <= cboDiameter.Items.Count-1; i++)
{
    if (cboDiameter.GetItemText(cboDiameter.Items[i]) == formPipe.diameter.ToString()) 
    {
        //this line never executes, even when there's seemingly a text match
        myIndex = i;
    }
}
cboDiameter.SelectedIndex = myIndex;

这是我用来分配管道直径的,但它被截断了。 (例如,当组合框文本为“1.0”时,管道直径被指定为“1”

//assign the value of the dropdown to the object
double.TryParse(cboDiameter.GetItemText(cboDiameter.SelectedItem), out value);
formPipe.diameter = value;

【问题讨论】:

  • 你确定formPipe.diameter.ToString() 返回一个带有" 的字符串吗?
  • 你比较字符串。 1.01 这样的字符串不相同。
  • 你需要使用.EndsWith函数或者.Contains.Split()
  • 你调试过你的代码吗?你发现了什么?
  • 威梅尔是正确的。 formPipe.diameter = 1.0,但是当我使用.ToString()方法时,它被截断为1。有没有办法避免这种截断?

标签: c# for-loop text-comparison


【解决方案1】:

不是 100% 确定为什么双精度会被截断为整数,但为了解决这个问题,我将组合框值解析为另一个双精度,然后比较两个双精度而不是比较字符串:

for (int i = 0; i <= cboDiameter.Items.Count-1; i++)
                {
                    double.TryParse(cboDiameter.GetItemText(cboDiameter.Items[i]), out val);
                    if (val == formPipe.diameter)
                    {
                        myIndex = i;
                    }
                }

【讨论】:

    猜你喜欢
    • 2013-09-06
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多