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

เมธอด Boolean.TryParse() ใน C#

เมธอด Boolean.TryParse() ใน C# ใช้สำหรับแปลงการแทนค่าสตริงของค่าตรรกะเป็นค่า Boolean เทียบเท่า โดยไม่ทำการโยนข้อยกเว้นหากการแปลงล้มเหลว

ไวยากรณ์

ไวยากรณ์มีดังนี้:

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

พารามิเตอร์:

  • val: สตริงที่ต้องการแปลง (เช่น "true", "false")
  • result: พารามิเตอร์เอาต์พุทที่จะเก็บค่า Boolean ที่แปลงได้

ค่าที่คืนกลับ: true หากการแปลงสำเร็จ, false หากการแปลงล้มเหลว

ตัวอย่าง

ตัวอย่างการใช้งานเมธอด Boolean.TryParse():

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

ผลลัพธ์

โค้ดจะแสดงผลดังนี้:

Result = True

ตัวอย่างเพิ่มเติม

ตัวอย่างที่สองกับค่าที่ไม่ใช่ Boolean:

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

ผลลัพธ์

โค้ดจะแสดงผลดังนี้:

Result = False