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

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

ฟิลด์ Int16.MaxValue ใน C# แทนค่าที่มากที่สุดที่เป็นไปได้ของ Int16 (คือ 32,767)

ไวยากรณ์

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

public const short MaxValue = 32767;

ตัวอย่าง

ตัวอย่างการใช้งานฟิลด์ Int16.MaxValue:

using System; 
public class Demo { 
    public static void Main(){ 
        short val1 = 23; 
        short val2 = 0; 
        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 = " + Int16.MaxValue); 
    } 
}

ผลลัพธ์

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

Value1 = 23 
Value2 = 0 
HashCode for value1 = 1507351 
HashCode for value2 = 0 
Are they equal? = False 
TypeCode for val1 = Int16 
TypeCode for val2 = Int16 
Maximum Value = 32767

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

ตัวอย่างการตรวจสอบช่วงค่าก่อนแปลง:

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

ผลลัพธ์

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

Converted: 8998 
Not Possible 
Not Possible 
Converted: -20