在C#中使用带有三元运算符的Console.Writeline

时间:2017-04-14 05:28:46

标签: c#

我正在尝试使用TryParse方法输出结果,但我仍然坚持如何使用三元输出来显示结果。有人可以帮忙.. ??

using System;
namespace Video1
{
    class Program
    {
        static void Main()
        {
            string number = "100.51yutr";
            int Result_of_Conversion = 0;
            bool is_Conversion_Successful = int.TryParse(number, out Result_of_Conversion);

            is_Conversion_Successful == true ? Console.WriteLine(Result_of_Conversion) : Console.WriteLine("Check"); 
        }
    }
}

2 个答案:

答案 0 :(得分:4)

替换

is_Conversion_Successful == true ? Console.WriteLine(Result_of_Conversion) : Console.WriteLine("Check");

使用

 Console.WriteLine(is_Conversion_Successful ? Result_of_Conversion.ToString() : "Check");

答案 1 :(得分:1)

更易读的方法

class Program 
{ 
    static void Main() 
    { 
       string number = "100.51yutr"; 
       int Result_of_Conversion = 0;
       bool is_Conversion_Successful = int.TryParse(number, out Result_of_Conversion);

        var result = is_Conversion_Successful ? Result_of_Conversion.ToString() : "Check";
        Console.WriteLine(result);
    }
}