我一直在尝试将我的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/