1. 程式人生 > >C# int、long、double、char等各種內建資料型別的位元組數、最大值、最小值

C# int、long、double、char等各種內建資料型別的位元組數、最大值、最小值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(byte).Name, sizeof(byte), byte.MinValue, byte.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(sbyte).Name, sizeof(sbyte), sbyte.MinValue, sbyte.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(short).Name, sizeof(short), short.MinValue, short.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(ushort).Name, sizeof(ushort), ushort.MinValue, ushort.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(int).Name, sizeof(int), int.MinValue, int.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(uint).Name, sizeof(uint), uint.MinValue, uint.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(long).Name, sizeof(long), long.MinValue, long.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(ulong).Name, sizeof(ulong), ulong.MinValue, ulong.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(float).Name, sizeof(float), float.MinValue, float.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(double).Name, sizeof(double), double.MinValue, double.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n", 
                                typeof(decimal).Name, sizeof(decimal), decimal.MinValue, decimal.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t\n", 
                                typeof(bool).Name, sizeof(bool));
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t 最小值:{2}\t 最大值:{3}\n",
                                typeof(char).Name, sizeof(char), char.MinValue, char.MaxValue);
            Console.WriteLine("{0}:\t 所佔位元組數: {1}\t ",
                                typeof(IntPtr).Name, IntPtr.Size);
            Console.ReadLine();
        }
    }
}

【測試結果】


【32位與64位】

唯一的不同是IntPtr型別在32位中為4個位元組,在64位中為8個位元組。

【對比C++】

C++中long與unsigned long為4個位元組,而在C#中為8個位元組