简体   繁体   English

如何确定字符串是否为int或double类型,以用于重载方法? C#

[英]How to determine if string is of type int or double, to used in overload method? C#

I want to call an overload method using the value that was inserted into my texbox. 我想使用插入到texbox中的值调用重载方法。 By default it is of value string, so I have to check if it is of type int or double. 默认情况下它是值字符串,所以我必须检查它是int还是double类型。 I am using the TryParse() to check and see if the values are of either int or double, but it causes me to have 2 variables for each textbox. 我正在使用TryParse()检查并查看值是int还是double,但是这使我每个文本框都有2个变量。 I only want the 2 variables that has been successful. 我只想要成功的2个变量。 I do not know how to determine which has been successful so that I can use them in the overload method call. 我不知道如何确定哪个成功,以便可以在重载方法调用中使用它们。

My code looks like this... 我的代码看起来像这样...

        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 I then nest the if else statements, the compiler gives me an error saying that the double value is unassigned. 如果再嵌套if else语句,则编译器会给我一个错误,指出未分配double值。 I know a bunch of if else statements are ugly code, but it is the only way I currently know how. 我知道一堆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...

The simplest form i can come up with is putting the TryParses in sequence in a single if statement and, handling the first one that succeeds. 我能想到的最简单的形式是将TryParses按顺序放在单个if语句中,并处理第一个成功的语句。

This leaves the possibility that one string cannot be parsed (or neither), so in that case i am throwing an exception 这留下了一个字符串无法解析(或都不解析)的可能性,因此在这种情况下,我抛出了异常

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM