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

ฟิลด์ Int32.MaxValue ใน C# พร้อมตัวอย่าง


บทนำ

ฟิลด์ Int32.MaxValue ใน C# แสดงค่าที่มากที่สุดที่เป็นไปได้ของจำนวนเต็ม 32 บิตที่มีเครื่องหมาย (int) ซึ่งมีค่าเท่ากับ 2,147,483,647

ไวยากรณ์ (Syntax)

public const int MaxValue = 2147483647;

ตัวอย่างที่ 1: แสดงค่าสูงสุดของ Int32

using System;

public class Demo 
{
    public static void Main()
    {
        int val1 = 23;
        int val2 = 23;
        
        Console.WriteLine("Value1 = " + val1);
        Console.WriteLine("Value2 = " + val2);
        Console.WriteLine("HashCode for value1 = " + val1.GetHashCode());
        Console.WriteLine("HashCode for value2 = " + val2.GetHashCode());
        Console.WriteLine("Are they equal? = " + val1.Equals(val2));
        
        TypeCode type1 = val1.GetTypeCode();
        TypeCode type2 = val2.GetTypeCode();
        Console.WriteLine("TypeCode for val1 = " + type1);
        Console.WriteLine("TypeCode for val2 = " + type2);
        
        Console.WriteLine("Maximum Value = " + Int32.MaxValue);
    }
}

ผลลัพธ์

Value1 = 23
Value2 = 23
HashCode for value1 = 23
HashCode for value2 = 23
Are they equal? = True
TypeCode for val1 = Int32
TypeCode for val2 = Int32
Maximum Value = 2147483647

ตัวอย่างที่ 2: ตรวจสอบขอบเขตก่อนแปลงจาก long เป็น int

using System;

public class Demo 
{
    public static void Main()
    {
        long[] val = { 8998, -899898778, 8787867687878, -20 };
        int res;
        
        foreach (long a in val)
        {
            if (a >= Int32.MinValue && a <= Int32.MaxValue)
            {
                res = Convert.ToInt32(a);
                Console.WriteLine("Converted: " + res);
            }
            else
            {
                Console.WriteLine("Not Possible");
            }
        }
    }
}

ผลลัพธ์

Converted: 8998
Converted: -899898778
Not Possible
Converted: -20

สรุป

ฟิลด์ Int32.MaxValue ใช้ร่วมกับ Int32.MinValue เพื่อตรวจสอบว่าค่าจะอยู่ในขอบเขตของ int ได้หรือไม่ ก่อนทำการแปลงชนิดข้อมูล ซึ่งช่วยป้องกันข้อผิดพลาดรันไทม์