此方法用于将指定的逻辑值的字符串表示形式转换为其等效的布尔值。它返回一个值,该值指示转换是成功还是失败。
句法:
public static bool TryParse (string value, out bool result);
参数:
value: It is a string containing the value to convert.
result: When this method returns, if the conversion succeeded, contains true if value is equal to TrueString or false if value is equal to FalseString. If the conversion failed, contains false. The conversion fails if the value is null or is not equal to the value of either the TrueString or FalseString field.
返回值:如果成功转换了值,则此方法返回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