我想使用插入到我的texbox中的值来调用重载方法。默认情况下它是值字符串,所以我必须检查它是int还是double类型。 我正在使用TryParse()检查并查看值是int还是double,但它导致每个文本框有2个变量。我只想要成功的2个变量。 我不知道如何确定哪个成功,以便我可以在重载方法调用中使用它们。
我的代码看起来像这样......
string a = textBox1.Text, b = textBox2.Text;
int f;
double d;
if(int.TryParse(a, out f))
{
}
else if(double.TryParse(a, out d))
{
}
int s;
double sD;
if (int.TryParse(b, out s))
{
}
else if(double.TryParse(b, out sD))
{
}
double x;
//Do not know which values to pass, because i only want the 2
//that was successful
Area(?, ?, out x);
label3.Text = "This is the value " + x;
}
private static void Area(int a, int b, out double x)
{
x = a * b;
}
private static void Area(double a, double b, out double x)
{
x = a * b;
}
private static void Area(int a, double b, out double x)
{
x = a * b;
}
如果我然后嵌套if else语句,编译器会给出一个错误,指出double值是未赋值的。我知道一堆if else语句是丑陋的代码,但这是我目前知道的唯一方法。
if(f == '\0' && s == '\0')
{ Area(d, sD, out sum); }
else if(d=='\0' && s=='\0')
{Area(f, sD, out sum;)}
//and so on...
答案 0 :(得分:1)
我能想到的最简单的形式是将TryParses按顺序放在一个if
语句中,然后处理第一个成功的。
这样就有可能无法解析一个字符串(或两者都没有),所以在这种情况下我抛出一个异常
int intA;
int intB;
double doubleA;
double doubleB;
double x;
if(int.TryParse(a, out intA) && int.TryParse(b, out intB))
{
Area(intA, intB, out x);
}
else if (double.TryParse(a, out doubleA) && double.TryParse(b, out doubleB))
{
Area(doubleA, doubleB, out x);
}
else
{
throw new ArgumentException("cannot parse one or both numbers");
}
label3.Text = "This is the value " + x;