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

C# 運算子大全:新增 checked/unchecked、is、sizeof 等進階運算子詳解

     編輯:關於C語言

運算子對照表

C# 支援 Java 所有運算子,並新增以下運算子:

分類符號
一元++ -- + - ! ~ ()
乘法* / %
加法+ -
位移<< >>
關係< > <= >= is
相等== !=
邏輯& ^ | && ||
條件? :
指派= *= /= %= += -= <<= >>= &= ^= |=
型別資訊typeof sizeof
溢位檢查checked unchecked

差異: Java 有 >>> 無號右移,C# 無此運算子,因 C# 支援無號型別,>> 會依操作數帶號與否自動處理。

checked / unchecked:溢位控制

整數運算溢位時,checked 拋出 OverflowException,unchecked 忽略溢位(預設行為)。常數運算式用 checked 會在編譯期報錯。

using System;

public class Class1
{
    public static void Main(string[] args)
    {
        short a = 10000, b = 10000;
        short d = unchecked((short)(10000 * 10000)); // 避免編譯錯誤
        Console.WriteLine(d);
        short c = (short)(a * b); // 預設 unchecked,靜默溢位
        Console.WriteLine(c);
        short e = checked((short)(a * b)); // 運行期拋出 OverflowException
        Console.WriteLine(e);
    }
}

執行時 d、c 均為 -7936,e 擲出例外。也可用編譯器參數 /checked 控制整個專案。

is 運算子:型別檢查

if (objReference is SomeClass) ...
using System;

public class ShowTypes
{
    public static void Main(string[] args)
    {
        CheckType(5);
        CheckType(10f);
        CheckType("Hello");
    }

    private static void CheckType(object obj)
    {
        if (obj is int) Console.WriteLine("Integer parameter");
        else if (obj is float) Console.WriteLine("Float parameter");
        else if (obj is string) Console.WriteLine("String parameter");
    }
}

sizeof 運算子:取得型別大小

using System;

public class Size
{
    public static void Main()
    {
        unsafe
        {
            Console.WriteLine("The size of short is {0}.", sizeof(short));
            Console.WriteLine("The size of int is {0}.", sizeof(int));
            Console.WriteLine("The size of double is {0}.", sizeof(double));
        }
    }
}

sizeof 需在 unsafe 區塊中使用,因直接存取記憶體。

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