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

คลาส Convert ใน C#

ภาพรวม

คลาส Convert จัดเตรียมเมธอดสแตติกสำหรับแปลงชนิดข้อมูลพื้นฐาน (base types) ระหว่างกัน เช่น ToBoolean, ToDouble, ToDecimal ฯลฯ

Convert.ToBoolean(String, IFormatProvider)

แปลงสตริงเป็น bool โดยใช้ข้อมูลวัฒนธรรม (culture)

public static bool ToBoolean(string val, IFormatProvider provider);

ตัวอย่าง

using System;
using System.Globalization;

public class Demo {
    public static void Main() {
        CultureInfo cultures = new CultureInfo("en-US");
        String str = "true";
        Console.WriteLine("Converted bool value...");
        bool res = Convert.ToBoolean(str, cultures);
        Console.Write("{0}", res);
    }
}

ผลลัพธ์

Converted bool value...
True

Convert.ToDouble(String, IFormatProvider)

แปลงสตริงเป็น double ด้วยรูปแบบเฉพาะวัฒนธรรม

public static double ToDouble(string val, IFormatProvider provider);

ตัวอย่าง

using System;
using System.Globalization;

public class Demo {
    public static void Main() {
        String val = "876876, 878";
        NumberFormatInfo formatProvider = new NumberFormatInfo();
        formatProvider.NumberDecimalSeparator = ", ";
        formatProvider.NumberGroupSeparator = ".";
        formatProvider.NumberGroupSizes = new int[] { 2 };
        Console.WriteLine("Converted Decimal value...");
        double res = Convert.ToDouble(val, formatProvider);
        Console.Write("{0}", res);
    }
}

ผลลัพธ์

Converted Decimal value...
876876.878

Convert.ToDecimal(String, IFormatProvider)

แปลงสตริงเป็น decimal ด้วยรูปแบบวัฒนธรรม

public static decimal ToDecimal(string val, IFormatProvider provider);

ตัวอย่าง

using System;
using System.Globalization;

public class Demo {
    public static void Main() {
        CultureInfo cultures = new CultureInfo("en-US");
        String val = "8787";
        Console.WriteLine("Converted Decimal value...");
        decimal res = Convert.ToDecimal(val, cultures);
        Console.Write("{0}", res);
    }
}

ผลลัพธ์

Converted Decimal value...
8787

สรุป

  • เมธอด Convert ต่างๆ รองรับ IFormatProvider สำหรับการแปลงที่ขึ้นกับวัฒนธรรม
  • โยน FormatException หรือ OverflowException หากแปลงไม่ได้
  • ครอบคลุมชนิดข้อมูลพื้นฐานทั้งหมด (bool, byte, char, DateTime, decimal, double, short, int, long, sbyte, float, string, uint, ulong, ushort)