如何通过在 C# 中使"out"变量可更改来定义方法?



下面的这些代码有效。但是它们很长,所以我想创建一个方法(还有很多其他的 TryParsing 要做,这只是一小部分(。

private void button_Click(object sender, EventArgs e)
{
bool resSPos = double.TryParse(txtSPos.Text, out double SPos);
if (resSPos == false) FalseBoolMsg("Starting Position");
bool resTPos = double.TryParse(txtTPos.Text, out double TPos);
if (resTPos == false) FalseBoolMsg("Target Position");
bool resIncr = double.TryParse(txtIncr.Text, out double Increment);
if (resIncr == false) FalseBoolMsg("Increment");
Ch.FunctionA(Ch.FunctionX, SomeInt, Increment, Ch.FunctionY);
Ch.FunctionB(SomeInt, SPos, Ch.FunctionY);
Ch.FunctionA(0, SomeInt, TPos, Ch.FunctionZ);             
}

"FalseBoolMsg"只是我在上级定义的用于生成MessageBox的方法。"txtSPos"、"txtTPos"和"txtIncr"只是我的Windows窗体中的文本框。无论如何,以下是我尝试但失败的。我已经尝试了几种变体,但无济于事。主要是,我对"double"参数的问题比字符串参数的问题更大。

private void TryParseDouble(string ParseTarget, string PointField, string FieldInMsg)
{
bool resBool = double.TryParse(ParseTarget, out double PointField);
if (resBool == false) FalseBoolMsg(FieldInMsg);
}
private void button_Click(object sender, EventArgs e)
{
TryParseDouble("txtSPos.Text", "SPos", "Starting Position");
TryParseDouble("txtTPos.Text", "TPos", "Target Position");
TryParseDouble("txtIncr.Text", "Increment", "Increment");
Ch.FunctionA(Ch.FunctionX, SomeInt, Increment, Ch.FunctionY);
Ch.FunctionB(SomeInt, SPos, Ch.FunctionY);
Ch.FunctionA(0, SomeInt, TPos, Ch.FunctionZ);             
}

是的,我可以在我的方法中将"字符串 PointField"更改为"双 PointField",但这意味着当我回忆起该方法时,我必须键入一个实际数字,而不是键入名称来替换"PointField"。我还需要函数来读取 TryParse 从我的方法中生成的"双名称"。感谢您的考虑。

编辑:多亏了约翰,我找到了答案(在 C# 中重命名变量的用户定义方法的正确方法或关键字是什么?

private bool TryParseDouble(string ParseTarget, out double PointField, string FieldInMsg)
{
if (!double.TryParse(ParseTarget, out PointField))
{
FalseBoolMsg(FieldInMsg);
return false;
}
return true;
}
private void button_Click(object sender, EventArgs e)
{
TryParseDouble(txtSPos.Text, out double SPos, "Starting Position");
}

虽然不完全清楚,但我认为您想根据方法中提供的参数替换TryParse()方法中的 out 变量名称。在这种情况下,您可以使用如下所示的switch语句。不过,看不出有任何理由这样做

private void TryParseDouble(string ParseTarget, string PointField, string FieldInMsg)
{
bool resBool; 
switch (PointField)
{
case "SPos":
resBool = double.TryParse(ParseTarget, out double SPos);
break;
case "TPos":
resBool = double.TryParse(ParseTarget, out double TPos);
break;
case "Increment":
resBool = double.TryParse(ParseTarget, out double Increment);
break;
default:              
break;
}
if (!resBool) FalseBoolMsg(FieldInMsg);
}

你应该这样称呼它

TryParseDouble(txtTPos.Text, "TPos", "Target Position");

最新更新