Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chuyển đổi chuỗi biểu diễn giá trị logic sang Boolean trong C#

Giới thiệu

Phương thức Boolean.TryParse(string, out bool) chuyển đổi chuỗi sang Boolean an toàn, không ném ngoại lệ. Trả về true nếu chuyển đổi thành công, false nếu thất bại. Chỉ chấp nhận "true" hoặc "false" (không phân biệt chữ hoa/thường).

Ví dụ 1: Chuyển đổi thành công

using System;

public class Demo
{
    public static void Main()
    {
        bool val;
        bool flag;
        val = Boolean.TryParse("true", out flag);
        Console.WriteLine("Result = " + val);
        Console.WriteLine("Parsed value = " + flag);
    }
}

Kết quả

Result = True
Parsed value = True

Ví dụ 2: Chuyển đổi thất bại

using System;

public class Demo
{
    public static void Main()
    {
        bool val;
        bool flag;
        val = Boolean.TryParse("$", out flag);
        Console.WriteLine("Result = " + val);
        Console.WriteLine("Parsed value = " + flag);
    }
}

Kết quả

Result = False
Parsed value = False

So sánh TryParse vs Parse vs Convert

Phương thức Thành công Thất bại Chấp nhận
Boolean.TryParse Trả về true, out = giá trị Trả về false, out = false "true", "false" (case-insensitive)
Boolean.Parse Trả về bool Ném FormatException "true", "false" (case-insensitive)
Convert.ToBoolean Trả về bool Ném FormatException "true", "false", null → false

Các chuỗi được chấp nhận

Boolean.TryParse("true", out _);    // True
Boolean.TryParse("True", out _);    // True
Boolean.TryParse("TRUE", out _);    // True
Boolean.TryParse("false", out _);   // True
Boolean.TryParse("False", out _);   // True
Boolean.TryParse("FALSE", out _);   // True
Boolean.TryParse("1", out _);       // False
Boolean.TryParse("0", out _);       // False
Boolean.TryParse("yes", out _);     // False
Boolean.TryParse("", out _);        // False
Boolean.TryParse(null, out _);      // False

Khuyến nghị

Luôn dùng TryParse khi nhập liệu từ người dùng hoặc nguồn không tin cậy để tránh exception.