首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 語法實戰(一):預定義資料型別範圍與預設值驗證代碼

     編輯:關於C#

驗證代碼:列印所有基礎型別 Min/Max/Mid 值

using System;

class MyClass
{
    static void Main()
    {
        // 整數家族
        PrintRange("sbyte",  sbyte.MinValue,  sbyte.MaxValue,  (sbyte.MaxValue + sbyte.MinValue) / 2);
        PrintRange("byte",   byte.MinValue,   byte.MaxValue,   (byte.MaxValue + byte.MinValue) / 2);
        PrintRange("short",  short.MinValue,  short.MaxValue,  (short.MaxValue + short.MinValue) / 2);
        PrintRange("ushort", ushort.MinValue, ushort.MaxValue, (ushort.MaxValue + ushort.MinValue) / 2);
        PrintRange("int",    int.MinValue,    int.MaxValue,    (int.MaxValue + int.MinValue) / 2);
        PrintRange("uint",   uint.MinValue,   uint.MaxValue,   (uint.MaxValue + uint.MinValue) / 2);
        PrintRange("long",   long.MinValue,   long.MaxValue,   (long.MaxValue + long.MinValue) / 2);
        PrintRange("ulong",  ulong.MinValue,  ulong.MaxValue,  (ulong.MaxValue + ulong.MinValue) / 2);

        // 浮點與 decimal
        PrintRange("float",   float.MinValue,   float.MaxValue,   (float.MaxValue + float.MinValue) / 2);
        PrintRange("double",  double.MinValue,  double.MaxValue,  (double.MaxValue + double.MinValue) / 2);
        PrintRange("decimal", decimal.MinValue, decimal.MaxValue, (decimal.MaxValue + decimal.MinValue) / 2);

        // char、bool、string
        Console.WriteLine("char 類型:");
        char c = '萬';
        Console.WriteLine($"{c}、{++c}\n");

        Console.WriteLine("bool 類型:");
        bool b = true;
        Console.WriteLine($"{b}、{!b}\n");

        Console.WriteLine("string 類型:");
        string s = "萬一的 Delphi 博客";
        Console.WriteLine($"{s}、Length: {s.Length}\n");

        Console.ReadKey();
    }

    static void PrintRange(string name, dynamic min, dynamic max, dynamic mid)
    {
        Console.WriteLine($"{name} 類型:");
        Console.WriteLine($"{min}、{mid}、{max}\n");
    }
}

輸出重點解析

  • 有號整數:中間值為 0(對稱範圍)
  • 無號整數:中間值為 Max/2
  • float/double:MinValue 為 負最大值(非最小正數),Mid 近似 0
  • decimal:128 位高精度,適合財務
  • char:單一 Unicode 字元,++c 產生下一碼位
  • string:參考型別,Length 回傳字元數(非位元組)

型別範圍速查表

型別位元範圍CLR 對應
sbyte8-128 ~ 127System.SByte
byte80 ~ 255System.Byte
short16-32,768 ~ 32,767System.Int16
ushort160 ~ 65,535System.UInt16
int32-2,147,483,648 ~ 2,147,483,647System.Int32
uint320 ~ 4,294,967,295System.UInt32
long64-9.22e18 ~ 9.22e18System.Int64
ulong640 ~ 1.84e19System.UInt64
float32±1.5e-45 ~ ±3.4e38System.Single
double64±5.0e-324 ~ ±1.7e308System.Double
decimal128±1.0e-28 ~ ±7.9e28System.Decimal
char16U+0000 ~ U+FFFFSystem.Char
bool1true/falseSystem.Boolean

控制台輸出結果圖

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved