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

Convert.ChangeType Method ใน C#: แปลงประเภทแบบ Dynamic

เมธอด Convert.ChangeType(object value, TypeCode typeCode) หรือ ChangeType(object value, Type conversionType) แปลง Object เป็นประเภทที่ระบุใน Runtime เหมาะสำหรับ Dynamic Conversion

ตัวอย่าง: Double to Int32

using System;

public class Demo
{
    public static void Main()
    {
        double val = -3.456;
        
        // แปลงเป็น Int32 (Truncate ทศนิยม)
        int num = (int)Convert.ChangeType(val, TypeCode.Int32);
        
        Console.WriteLine($"{val} converted to Int32: {num}");
    }
}

ผลลัพธ์

-3.456 converted to Int32: -3

Overloads

// ใช้ TypeCode (Enum)
object result1 = Convert.ChangeType(value, TypeCode.Int32);
object result2 = Convert.ChangeType(value, TypeCode.String);
object result3 = Convert.ChangeType(value, TypeCode.DateTime);

// ใช้ Type (Runtime Type)
Type targetType = typeof(DateTime);
object result4 = Convert.ChangeType(value, targetType);

// พร้อม IFormatProvider (Culture)
object result5 = Convert.ChangeType("1,234.56", TypeCode.Double, new CultureInfo("en-US")); // 1234.56
object result6 = Convert.ChangeType("1.234,56", TypeCode.Double, new CultureInfo("de-DE")); // 1234.56

TypeCode Enum Values

  • Empty, Object, DBNull, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, String

ข้อจำกัด

  • Object ต้อง Implement IConvertible
  • Custom Struct/Class ไม่ทำงาน (ต้อง Implement IConvertible เอง - ยุ่งยาก)
  • ไม่รองรับ Nullable Types โดยตรง (ต้อง Unwrap ก่อน)
  • Performance ช้ากว่า Direct Cast/Parse

ทางเลือกที่ดีกว่า

// Direct Cast (Compile-time)
int i = (int)doubleVal;

// Parse/TryParse (String)
int i = int.Parse("123");
bool ok = int.TryParse("123", out int i);

// Convert Class (Specific)
int i = Convert.ToInt32(doubleVal);

// TypeConverter (สำหรับ Custom Types, XAML, PropertyGrid)
var converter = TypeDescriptor.GetConverter(typeof(MyType));
MyType obj = (MyType)converter.ConvertFromString("value");

ใช้ ChangeType เมื่อ: Type ถูกกำหนดใน Runtime (Plugin, Configuration, Dynamic Data)