C# while循环中的if语句如何在用户输入有效数据时中断

C# while循环中的if语句如何在用户输入有效数据时中断,c#,while-loop,break,C#,While Loop,Break,我想知道在if语句的括号中放些什么来告诉程序,如果x或y等于double,它可以中断并继续执行我的其余代码 有什么建议吗 while (true) { Console.Write("I need to pour this much from this one: "); string thisOne = Console.ReadLine(); Double.TryParse(thisOne, out x); if ( /*

我想知道在if语句的括号中放些什么来告诉程序,如果x或y等于double,它可以中断并继续执行我的其余代码

有什么建议吗

while (true)
{                    
    Console.Write("I need to pour this much from this one: ");

    string thisOne = Console.ReadLine();
    Double.TryParse(thisOne, out x);

    if ( /* Here I want to put "x is a number/double*/ )
    {
        break;
    }

}

while (true)
{
    Console.Write("I need to pour this much from that one: ");

    string thatOne = Console.ReadLine();
    Double.TryParse(thatOne, out y);

    if (/* Here I want to put "y is a number/double*/)
    {
        break;
    }
}

TryParse返回一个布尔值来说明解析是否成功

if (Double.TryParse(thatOne, out y))
{
    break;
}

返回值指示转换是成功还是失败

Double.TryParse返回一个布尔值,非常适合您的if语句

if (Double.TryParse(thatOne, out y)) {
    break;
}

用bool控制循环,当条件满足时将bool设置为false

bool running = true;
while (running)
{                    
    Console.Write("I need to pour this much from this one: ");

    string thisOne = Console.ReadLine();

    if (Double.TryParse(thisOne, out y))
    {
         running = false
    }
}

根据,如果解析成功,TryParse将返回true,因此只需将TryParse放入if语句。

您对TryParse有误解。您要检查x是否为双精度。在上面代码的某个地方,您没有在这里发布它,可能有一行类似于double x=0;。 您已将x和y定义为双精度。您想检查您的字符串输入是否可以解析为双精度:

简写版本如下:

if (Double.TryParse(thatOne, out x))
{
    break;
}
这也可以写成:

bool isThisOneDouble = Double.TryParse(thisOne, out x);

if (isThisOneDouble)
{
    break;
}
如果您真的想检查某个变量是否属于某种类型,而不想对其进行解析,请按如下方式进行尝试:

double x = 3;
bool isXdouble = x.GetType() == typeof(double); 


我的建议是读这本书。提示:它返回一个布尔值。似乎是一个不必要的步骤?这也要求循环执行完整的迭代,OP可能希望提前爆发。它也没有回答if语句中包含的内容。只是编辑为包含,没有回答原始问题中的问题。最后一步是中断,以便不添加额外的执行。
double x = 3;
if(x.GetType() == typeof(double)) 
{
   // do something
}