📜  C#| Boolean.TryParse()方法

📅  最后修改于: 2021-05-29 21:50:43             🧑  作者: Mango

此方法用于将指定的逻辑值的字符串表示形式转换为其等效的布尔值。它返回一个值,该值指示转换是成功还是失败。

句法:

public static bool TryParse (string value, out bool result);

参数:

返回值:如果成功转换了值,则此方法返回true ,否则返回false

下面的程序说明了Boolean.TryParse(String,Boolean)方法的用法:

范例1:

// C# program to demonstrate
// Boolean.TryParse(String, Boolean)
// Method
using System;
  
class GFG {
  
// Main Method
public static void Main() {
  
        // passing different values 
        // to the method to check
        checkParse("true");
        checkParse("false");
        checkParse("'     true     '");
        checkParse(" $  ");
        checkParse("1");
    }
  
// Declaring checkparse method
public static void checkParse(string value) {
  
        // Declaring data type
        bool result;
        bool flag;
   
        // using the method
        result = Boolean.TryParse(value, out flag);
  
        // Display boolean type result
        Console.WriteLine("{0} --> {1} ", value, result);
    }
}
输出:
true --> True 
false --> True 
'     true     ' --> False 
 $   --> False 
1 --> False

范例2:

// C# program to demonstrate
// Boolean.TryParse(String, Boolean)
// Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // passing different values 
        // to the method to check
        checkParse("true1");
        checkParse(null);
        checkParse(String.Empty);
    }
  
// Declaring checkparse method
public static void checkParse(string value) {
  
        // Declaring data type
        bool result;
        bool flag;
   
        // using the method
        result = Boolean.TryParse(value, out flag);
  
        // Display boolean type result
        Console.WriteLine("{0} --> {1} ", value, result);
    }
}
输出:
true1 --> False 
 --> False 
 --> False

注意: TryParse方法类似于Parse方法,但是如果转换失败,TryParse方法不会引发异常。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.boolean.tryparse?view=netframework-4.7.2