此方法用於將指定的邏輯值的字符串表示形式轉換為其等效的布爾值。它返回一個值,該值指示轉換是成功還是失敗。
用法:
public static bool TryParse (string value, out bool result);
參數:
- value:它是一個包含要轉換的值的字符串。
- result:當此方法返回時,如果轉換成功,則在value等於TrueString時包含true,或者在value等於FalseString時包含false。如果轉換失敗,則包含false。如果該值為null或不等於TrueString或FalseString字段的值,則轉換失敗。
返回值:如果成功轉換了值,則此方法返回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方法不會引發異常。
參考:
相關用法
- C# DateTimeOffset.Add()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# Math.Sin()用法及代碼示例
- C# Math.Cos()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Tan()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 C# | Boolean.TryParse() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。