Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การแปลงสตริงเป็น bool ใน C# ด้วย bool.Parse()

เมธอด bool.Parse() ใช้แปลงสตริงที่แสดงค่าจริง/เท็จ ให้กลายเป็นชนิดข้อมูล bool รองรับค่า "true" และ "false" (ไม่สนใจตัวพิมพ์เล็ก/ใหญ่)

รูปแบบการใช้งาน

string str = "false";
bool value = bool.Parse(str); // false

โค้ดตัวอย่างสมบูรณ์

using System;

class Demo
{
    static void Main()
    {
        string[] testValues = { "true", "false", "True", "FALSE", "TrUe", "FaLsE" };
        
        Console.WriteLine("การแปลงค่ามาตรฐาน:");
        foreach (var s in testValues)
        {
            try
            {
                bool result = bool.Parse(s);
                Console.WriteLine($"  '{s}' → {result}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  '{s}' → ERROR: {ex.Message}");
            }
        }
        
        // ค่าที่จะทำให้เกิดข้อผิดพลาด
        Console.WriteLine("\nค่าที่ไม่ถูกต้อง:");
        string[] invalid = { "yes", "no", "1", "0", "on", "off", "", "null" };
        foreach (var s in invalid)
        {
            try
            {
                bool result = bool.Parse(s);
                Console.WriteLine($"  '{s}' → {result}");
            }
            catch (FormatException)
            {
                Console.WriteLine($"  '{s}' → FormatException (ไม่รองรับ)");
            }
        }
    }
}

ผลลัพธ์

การแปลงค่ามาตรฐาน:
  'true' → True
  'false' → False
  'True' → True
  'FALSE' → False
  'TrUe' → True
  'FaLsE' → False

ค่าที่ไม่ถูกต้อง:
  'yes' → FormatException (ไม่รองรับ)
  'no' → FormatException (ไม่รองรับ)
  '1' → FormatException (ไม่รองรับ)
  '0' → FormatException (ไม่รองรับ)
  'on' → FormatException (ไม่รองรับ)
  'off' → FormatException (ไม่รองรับ)
  '' → FormatException (ไม่รองรับ)
  'null' → FormatException (ไม่รองรับ)

เมธอดแปลงที่เกี่ยวข้อง

เมธอดคำอธิบายค่าที่รองรับ
bool.Parse()แปลงสตริงเป็น bool"true", "false" (case-insensitive)
bool.TryParse()พยายามแปลง คืน boolเหมือน Parse แต่ไม่โยน Exception
Convert.ToBoolean()แปลงจาก object ใดๆรองรับกว้างกว่า: "true"/"false", 1/0, null

Convert.ToBoolean() - ยืดหยุ่นกว่า

object[] values = { true, false, "true", "false", "True", "1", "0", 1, 0, -1, null };

foreach (var v in values)
{
    bool result = Convert.ToBoolean(v);
    Console.WriteLine($"  {v?.GetType().Name,-8} {v?.ToString() ?? "null",-6} → {result}");
}

ผลลัพธ์ Convert.ToBoolean()

  Boolean  True   → True
  Boolean  False  → False
  String   true   → True
  String   false  → False
  String   True   → True
  String   1      → True
  String   0      → False
  Int32    1      → True
  Int32    0      → False
  Int32    -1     → True
  null     null   → False

แนะนำ: ใช้ TryParse สำหรับ Input จากผู้ใช้

Console.Write("ป้อน true/false: ");
string input = Console.ReadLine();

if (bool.TryParse(input, out bool flag))
{
    Console.WriteLine($"ค่าที่ได้: {flag}");
}
else
{
    Console.WriteLine("กรุณาป้อน 'true' หรือ 'false' เท่านั้น");
}

ข้อควรระวัง

  • bool.Parse() รองรับ เฉพาะ "true" และ "false" (ไม่สนใจพิมพ์เล็ก/ใหญ่)
  • ไม่รองรับ "1"/"0", "yes"/"no", "on"/"off" - ต้องใช้ Convert.ToBoolean() หรือแปลงเอง
  • สตริงว่างหรือ null จะโยน FormatException / ArgumentNullException
  • ช่องว่างนำหน้า/ท้าย จะถูกตัดทิ้งอัตโนมัติ