【发布时间】:2018-05-16 11:55:45
【问题描述】:
下面的这些代码有效。但是它们很长,所以我想创建一个方法(很多其他的 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);
}
是的,我可以在我的方法中将“string PointField”更改为“double PointField”,但这意味着当我调用该方法时,我必须输入一个实际数字,而不是输入名称来替换“PointField”。我还需要从我的方法中读取 TryParse 生成的“双重名称”的函数。感谢您的考虑。
编辑:感谢 John (What is the proper method or keyword to put in a user-defined method that renames a variable in 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");
}
【问题讨论】:
-
我假设
SPosTPos和Increment是同一类的属性? -
顺便说一句
"txtSPos.Text"应该是txtSPos.Text -
双参数有什么问题。恐怕根本不清楚。我也不明白:“我在回忆方法时必须输入一个实际数字”
-
我认为他正在使用自动属性,这就是为什么他不能将其传递出去
-
嗨 Sebastian,如果您看到工作代码,SPos、TPos 和 Increment 只是我为“out doubles”提供的名称。只要我记得函数中的相同名称,我就可以在“out double”中为它们命名任何我喜欢的名称。嗨 Rahul,感谢您的提示,但我仍然想不出一种方法来完成所有这些工作。
标签: c# methods double tryparse