c# - 使用int.TryParse C#时发生编译错误

标签 c# winforms compiler-errors

我一直在尝试将我的int.parse更改为int.tryparse,因为我听说这是一个更好的方法。我不断收到错误,我真的不知道我在做什么错。

int index = this.Controls.GetChildIndex(WorkflowStepPanel, false);
this.Controls.SetChildIndex(WorkflowStepPanel, 
int.Parse(WorkflowStepPanel.indexBox.Text));

我尝试了这段代码:
 int index = this.Controls.GetChildIndex(WorkflowStepPanel, false);
 this.Controls.SetChildIndex(WorkflowStepPanel, 
 int.TryParse(WorkflowStepPanel.indexBox.Text));

但是得到这个编译错误:

CS1501 No overload for method 'TryParse' takes 1 arguments

最佳答案

只要能够将输入转换为整数,Int32.TryParse就会返回一个 bool(boolean) 值。您可以利用这种行为避免程序由于用户输入的无效数据而生成运行时异常,如下所示:

int newIndex = 0;
if (Int32.TryParse(WorkflowStepPanel.indexBox.Text, out newIndex))
{
    int index = this.Controls.GetChildIndex(WorkflowStepPanel, false);
    this.Controls.SetChildIndex(WorkflowStepPanel, newIndex);
}
else
{
    MessageBox.Show(String.Format(
        "You entered {0} and that's not a valid number", 
        WorkflowStepPanel.indexBox.Text));
}

通过尝试将第一个参数转换为整数值,此TryParse方法可以正常工作。如果成功,则将解析后的值放入out变量中,该方法将返回true。如果输入无效,则该方法将返回false,并将out变量设置为零。

您的代码正在生成错误,可能是因为SetChildIndex方法要求使用整数而不是 bool(boolean) 值。

关于c# - 使用int.TryParse C#时发生编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45554252/

相关文章:

c# - 来自幕后的绑定(bind)错误

c# - 为什么 EF 5.0 在编译为 sql 时不支持此 EF 4.x LINQ 语法?

c# - 用 SQL 列填充 WPF 组合框

c++ - 对 `vtable for DigitalClock' 的 undefined reference - 对 `DigitalClock::staticMetaObject' 的 undefined reference - Qt

c++ - Qt "no matching function for call"

c# - 在 .Net 2.0 中关闭 SerialPort 时出现 ObjectDisposedException

C# anchor 属性似乎不起作用

c# - 将 dataGridView 绑定(bind)到绑定(bind)列表并按文本框过滤行

c# - 在下游生成新的 Windows 窗体时如何使用 DI?

gcc - 可以在没有自由的情况下构建 binutils 吗?或者report_times可以禁用吗?