蓝色天空.知识 · 实践 · 创造
我的收藏
C# 教程目录 42章
C# / LEARN BY DOING

C# 运算符

全面梳理 C# 算术、关系、逻辑、位运算、赋值及其他特殊运算符(sizeof/typeof/is/as/?:),并给出完整运算符优先级与结合性参考表及本地全量实测。

学完这一章,你能够

  • 全面梳理 C# 算术、关系、逻辑、位运算、赋值及其他特殊运算符(sizeof/typeof/is/as/?:),并给出完整运算符优先级与结合性参考表及本地全量实测。

运算符分类、算术运算与自增自减

运算符用于指示编译器对一个或多个操作数执行特定的数学、比较、逻辑或位级操作。C# 内置运算符系统划分为六大类别:算术运算符、关系运算符、逻辑运算符、位运算符、赋值运算符以及其他特殊运算符,下文将逐类解析并实测验证。

算术运算符包含 `+`、`-`、`*`、`/`、`%` 以及自增 `++` 与自减 `--`(整数除法会向零截断小数部分)。需特别区分前置与后置写法:`c = a++` 先把原值赋给 `c` 再将 `a` 加 1;`c = ++a` 先把 `a` 加 1 再赋给 `c`;`c = a--` 先赋值再减 1;`c = --a` 先减 1 再赋值。本站 `ExploreOperators.cs` 已对 `a=21, b=10` 全部算术结果(`31, 11, 210, 2, 1, 22, 21`)以及四组自增自减中间状态(`a=2,b=1` / `a=2,b=2` / `a=0,b=1` / `a=0,b=0`)完成精确验证。

关系运算符与逻辑运算符

关系运算符用于比较两个操作数的大小或相等性并返回 `bool` 结果,包含 `==`、`!=`、`>`、`<`、`>=`、`<=`。在实测案例中,当 `a=21, b=10` 时 `a == b` 与 `a < b` 为假、`a > b` 为真;改设 `a=5, b=20` 后 `a <= b` 与 `b >= a` 均为真。

逻辑运算符作用于 `bool` 表达式:逻辑与 `&&` 在两侧均为 `true` 时为真,逻辑或 `||` 在任一侧为 `true` 时为真,逻辑非 `!` 对布尔状态取反(注:C# 是强类型语言,条件逻辑运算符仅接受 `bool` 操作数,不支持像 C/C++ 那样直接拿非零整数充当真值)。同时 `&&` 与 `||` 具备短路求值特性,本站实测确认 `false && fn()` 与 `true || fn()` 均不会调用右侧函数。

位运算符与复合赋值运算符

位运算符直接对整数二进制补码的每一位逐位操作,包括按位与 `&`、按位或 `|`、按位异或 `^`、一元按位取反 `~` 以及左移 `<<`、右移 `>>`。以 `A = 60`(`0011 1100`)与 `B = 13`(`0000 1101`)为例:`A & B = 12`(`0000 1100`)、`A | B = 61`(`0011 1101`)、`A ^ B = 49`(`0011 0001`)、`~A = -61`(32 位有符号补码翻转所有位含符号位)、`A << 2 = 240`、`A >> 2 = 15`。本站实验已逐行核对真值表与上述六项二进制结果。

赋值运算符除简单赋值 `=` 外,还提供 10 种复合赋值简写:`+=`、`-=`、`*=`、`/=`、`%=`、`<<=`、`>>=`、`&=`、`^=`、`|=`,把运算与写回左值合二为一。本站实测从 `a = 21` 依次执行 11 步赋值序列,精确得到 `[21, 42, 21, 441, 21, 11, 44, 11, 2, 0, 2]`。

其他特殊运算符与运算符优先级

C# 还提供若干关键特殊运算符:`sizeof(T)` 返回非托管值类型字节大小(如 `int=4`、`short=2`、`double=8`);`typeof(T)` 在编译期获取对应 `System.Type` 元数据对象(例如 `typeof(string).FullName` 返回 `System.String`,常用于反射与动态实例化);三元条件运算符 `? :` 按布尔条件二选一求值;`is` 检测对象是否为指定类型或子类型;`as` 执行安全引用转换且失败时返回 `null` 而不抛出异常;取址 `&` 与解引用 `*` 指针运算符仅限 `unsafe` 上下文使用。

运算符优先级决定复合表达式中各项的结合顺序:例如 `7 + 3 * 2` 先算乘法得 `13` 而非 `20`;逻辑运算中 `&&` 高于 `||`;关系比较高于三元条件,而复合赋值 `a += b * c` 会先计算右侧乘法再执行累加赋值。括号 `()` 可显式覆盖默认优先级:在 `a=20, b=10, c=15, d=5` 时,`(a + b) * c / d` 与 `(a + b) * (c / d)` 得 `90`,而 `a + (b * c) / d` 得 `50`。工程编码中建议善用圆括号明确意图,避免依赖隐晦优先级表导致误读。

C# 算术运算符参考表(以 A=10, B=20 为例)

运算符作用描述运算示例
`+`计算两个操作数之和A + B 结果为 30
`-`第一操作数减去第二操作数A - B 结果为 -10
`*`计算两个操作数之积A * B 结果为 200
`/`相除(两整数相除截断小数)B / A 结果为 2
`%`取模,返回整除后的余数B % A 结果为 0
`++`自增运算符,操作数加 1A 自增后变为 11
`--`自减运算符,操作数减 1A 自减后变为 9

C# 关系运算符参考表(以 A=10, B=20 为例)

运算符作用描述比较结果示例
`==`检查两个操作数是否相等(A == B) 为 false
`!=`检查两个操作数是否不等(A != B) 为 true
`>`检查左操作数是否大于右操作数(A > B) 为 false
`<`检查左操作数是否小于右操作数(A < B) 为 true
`>=`检查左操作数是否大于或等于右操作数(A >= B) 为 false
`<=`检查左操作数是否小于或等于右操作数(A <= B) 为 true

C# 逻辑运算符参考表(以 A=true, B=false 为例)

运算符作用描述布尔结果示例
`&&`短路逻辑与:两侧布尔操作数均为 true 时返回 true(A && B) 为 false
`||`短路逻辑或:任一侧布尔操作数为 true 时返回 true(A || B) 为 true
`!`逻辑非:翻转布尔操作数的真假状态!(A && B) 为 true

按位与 / 或 / 异或真值表

pqp & qp | qp ^ q
00000
01011
11110
10011

C# 位运算符参考表(以 A=60, B=13 为例)

运算符作用描述位运算结果示例
`&`按位与:对应二进制位同为 1 时结果位为 1A & B = 12 (0000 1100)
`|`按位或:对应二进制位任一为 1 时结果位为 1A | B = 61 (0011 1101)
`^`按位异或:对应二进制位不同时结果位为 1A ^ B = 49 (0011 0001)
`~`按位取反:翻转所有二进制位(含符号位)~A = -61(32 位有符号补码)
`<<`左移:各位左移指定位数,低位补 0A << 2 = 240 (1111 0000)
`>>`右移:各位右移指定位数(有符号数执行算术右移)A >> 2 = 15 (0000 1111)

C# 赋值与复合赋值运算符参考表

运算符作用描述等价展开示例
`=`简单赋值,将右侧值写入左侧变量C = A + B
`+=`加且赋值C += A 等价于 C = C + A
`-=`减且赋值C -= A 等价于 C = C - A
`*=`乘且赋值C *= A 等价于 C = C * A
`/=`除且赋值C /= A 等价于 C = C / A
`%=`取模且赋值C %= A 等价于 C = C % A
`<<=`左移且赋值C <<= 2 等价于 C = C << 2
`>>=`右移且赋值C >>= 2 等价于 C = C >> 2
`&=`按位与且赋值C &= 2 等价于 C = C & 2
`^=`按位异或且赋值C ^= 2 等价于 C = C ^ 2
`|=`按位或且赋值C |= 2 等价于 C = C | 2

C# 其他重要特殊运算符参考表

运算符作用描述用法示例
`sizeof()`返回内置非托管值类型的字节尺寸`sizeof(int)` 返回 4
`typeof()`编译期获取指定类型的 `System.Type` 对象`typeof(string)` / `typeof(StreamReader)`
`&`(取址)在 `unsafe` 上下文中获取变量的内存地址`&a;`(需 `/unsafe`)
`*`(解引用)在 `unsafe` 上下文中声明或解引用指针`*a;`(需 `/unsafe`)
`? :`三元条件表达式,按真假二选一求值`cond ? X : Y`
`is`判断对象运行时是否兼容指定类型`if (ford is Car)`
`as`安全引用转换,类型不匹配时返回 `null` 而不抛异常`StringReader r = obj as StringReader;`

C# 运算符优先级与结合性参考表(从高到低)

优先级类别包含运算符结合性
后缀 / 基本`() [] -> . ++ --`从左到右
一元`+ - ! ~ ++ -- (type) * & sizeof`从右到左
乘除取模`* / %`从左到右
加减`+ -`从左到右
位移`<< >>`从左到右
关系比较`< <= > >=`从左到右
相等比较`== !=`从左到右
按位与`&`从左到右
按位异或`^`从左到右
按位或`|`从左到右
条件逻辑与`&&`从左到右
条件逻辑或`||`从左到右
三元条件`?:`从右到左
赋值与复合赋值`= += -= *= /= %= >>= <<= &= ^= |=`从右到左
分隔符(原表末行)`,`(注:C# 无 C 风格通用逗号运算符,主要用于实参/声明/for 分隔)从左到右

全量实测算术自增减、关系、短路逻辑、位运算、11 步复合赋值、特殊运算符与优先级

含完整源码 · 274 行
展开查看收起
csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;

public class ExploreOperators
{
    private class Vehicle { }
    private class Car : Vehicle { }

    private static string JsonEscape(string s)
    {
        if (s == null) return "null";
        StringBuilder sb = new StringBuilder();
        sb.Append('"');
        for (int i = 0; i < s.Length; i++)
        {
            char c = s[i];
            switch (c)
            {
                case '"': sb.Append("\\\""); break;
                case '\\': sb.Append("\\\\"); break;
                case '\b': sb.Append("\\b"); break;
                case '\f': sb.Append("\\f"); break;
                case '\n': sb.Append("\\n"); break;
                case '\r': sb.Append("\\r"); break;
                case '\t': sb.Append("\\t"); break;
                default:
                    if (c < 0x20)
                        sb.Append(string.Format(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)c));
                    else
                        sb.Append(c);
                    break;
            }
        }
        sb.Append('"');
        return sb.ToString();
    }

    private static string MakeCase(string name, string summary, string expectedJson, string actualJson)
    {
        bool passed = string.Equals(expectedJson, actualJson, StringComparison.Ordinal);
        return string.Format(
            CultureInfo.InvariantCulture,
            "{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
            JsonEscape(name),
            JsonEscape(summary),
            expectedJson,
            actualJson,
            passed ? "true" : "false"
        );
    }

    public static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

        List<string> cases = new List<string>();

        // Case 1: Arithmetic operators and prefix/postfix ++ / --
        int a1 = 21, b1 = 10;
        int add = a1 + b1;
        int sub = a1 - b1;
        int mul = a1 * b1;
        int div = a1 / b1;
        int mod = a1 % b1;
        int preInc = ++a1; // 22
        int preDec = --a1; // 21

        int x = 1; int postIncVal = x++; int xAfterPostInc = x; // (1, 2)
        x = 1; int preIncVal = ++x; int xAfterPreInc = x;       // (2, 2)
        x = 1; int postDecVal = x--; int xAfterPostDec = x;     // (1, 0)
        x = 1; int preDecVal = --x; int xAfterPreDec = x;       // (0, 0)

        string actualArith = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"ops\":[{0},{1},{2},{3},{4},{5},{6}],\"incdec\":[{7},{8},{9},{10},{11},{12},{13},{14}]}}",
            add, sub, mul, div, mod, preInc, preDec,
            xAfterPostInc, postIncVal, xAfterPreInc, preIncVal,
            xAfterPostDec, postDecVal, xAfterPreDec, preDecVal
        );
        string expectedArith = "{\"ops\":[31,11,210,2,1,22,21],\"incdec\":[2,1,2,2,0,1,0,0]}";
        cases.Add(MakeCase(
            "arithmetic_and_inc_dec",
            "实测加减乘除取模及前置/后置自增自减在赋值前后的精确变化",
            expectedArith,
            actualArith
        ));

        // Case 2: Relational operators
        int ra = 21, rb = 10;
        bool eq = (ra == rb);
        bool neq = (ra != rb);
        bool lt = (ra < rb);
        bool gt = (ra > rb);
        ra = 5; rb = 20;
        bool le = (ra <= rb);
        bool ge = (rb >= ra);
        string actualRel = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"eq\":{0},\"neq\":{1},\"lt\":{2},\"gt\":{3},\"le\":{4},\"ge\":{5}}}",
            eq ? "true" : "false",
            neq ? "true" : "false",
            lt ? "true" : "false",
            gt ? "true" : "false",
            le ? "true" : "false",
            ge ? "true" : "false"
        );
        string expectedRel = "{\"eq\":false,\"neq\":true,\"lt\":false,\"gt\":true,\"le\":true,\"ge\":true}";
        cases.Add(MakeCase(
            "relational_operators",
            "实测 ==、!=、<、>、<=、>= 六种关系比较运算符布尔结果",
            expectedRel,
            actualRel
        ));

        // Case 3: Logical operators and short-circuit evaluation
        bool la = true, lb = true;
        bool r1 = la && lb;
        bool r2 = la || lb;
        la = false; lb = true;
        bool r3 = la && lb;
        bool r4 = !(la && lb);
        int rhsCalls = 0;
        Func<bool> touchRhs = delegate() { rhsCalls++; return true; };
        bool scAnd = false && touchRhs();
        bool scOr = true || touchRhs();
        string actualLog = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"r1\":{0},\"r2\":{1},\"r3\":{2},\"r4\":{3},\"sc_and\":{4},\"sc_or\":{5},\"rhs_calls\":{6}}}",
            r1 ? "true" : "false",
            r2 ? "true" : "false",
            r3 ? "true" : "false",
            r4 ? "true" : "false",
            scAnd ? "true" : "false",
            scOr ? "true" : "false",
            rhsCalls
        );
        string expectedLog = "{\"r1\":true,\"r2\":true,\"r3\":false,\"r4\":true,\"sc_and\":false,\"sc_or\":true,\"rhs_calls\":0}";
        cases.Add(MakeCase(
            "logical_operators_and_short_circuit",
            "实测 &&、||、! 逻辑运算与左侧决定结果时的短路求值机制",
            expectedLog,
            actualLog
        ));

        // Case 4: Bitwise truth table and bitwise operators
        int[,] pairs = new int[,] { { 0, 0 }, { 0, 1 }, { 1, 1 }, { 1, 0 } };
        List<string> tt = new List<string>();
        for (int i = 0; i < 4; i++)
        {
            int p = pairs[i, 0], q = pairs[i, 1];
            tt.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", p & q, p | q, p ^ q));
        }
        int ba = 60; // 0011 1100
        int bb = 13; // 0000 1101
        string actualBit = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"truth\":{0},\"and\":{1},\"or\":{2},\"xor\":{3},\"not\":{4},\"shl\":{5},\"shr\":{6}}}",
            JsonEscape(string.Join(",", tt.ToArray())),
            ba & bb,
            ba | bb,
            ba ^ bb,
            ~ba,
            ba << 2,
            ba >> 2
        );
        string expectedBit = "{\"truth\":\"000,011,110,011\",\"and\":12,\"or\":61,\"xor\":49,\"not\":-61,\"shl\":240,\"shr\":15}";
        cases.Add(MakeCase(
            "bitwise_operators_and_truth_table",
            "实测 &/|/^ 位真值表与 60/13 的按位与、或、异或、取反及左右移运算",
            expectedBit,
            actualBit
        ));

        // Case 5: Assignment and compound assignment operators
        int aa = 21;
        int c = aa; int s1 = c;
        c += aa; int s2 = c;
        c -= aa; int s3 = c;
        c *= aa; int s4 = c;
        c /= aa; int s5 = c;
        c = 200;
        c %= aa; int s6 = c;
        c <<= 2; int s7 = c;
        c >>= 2; int s8 = c;
        c &= 2; int s9 = c;
        c ^= 2; int s10 = c;
        c |= 2; int s11 = c;
        string actualAssign = string.Format(
            CultureInfo.InvariantCulture,
            "[{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}]",
            s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11
        );
        string expectedAssign = "[21,42,21,441,21,11,44,11,2,0,2]";
        cases.Add(MakeCase(
            "assignment_operators",
            "逐步实测 =、+=、-=、*=、/=、%=、<<=、>>=、&=、^=、|= 共 11 种赋值运算序列",
            expectedAssign,
            actualAssign
        ));

        // Case 6: Other operators (sizeof, typeof, ?:, is, as)
        int tA = 10;
        int tB1 = (tA == 1) ? 20 : 30;
        int tB2 = (tA == 10) ? 20 : 30;
        Type strType = typeof(string);
        Vehicle ford = new Car();
        bool fordIsCar = ford is Car;
        object srObj = new StringReader("Hello");
        StringReader srCast = srObj as StringReader;
        Car badAs = srObj as Car;
        string actualOther = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"sizes\":[{0},{1},{2}],\"ternary\":[{3},{4}],\"typeof_string\":{5},\"is_car\":{6},\"as_ok\":{7},\"as_fail_null\":{8}}}",
            sizeof(int), sizeof(short), sizeof(double),
            tB1, tB2,
            JsonEscape(strType.FullName),
            fordIsCar ? "true" : "false",
            (srCast != null && srCast.ReadToEnd() == "Hello") ? "true" : "false",
            (badAs == null) ? "true" : "false"
        );
        string expectedOther = "{\"sizes\":[4,2,8],\"ternary\":[30,20],\"typeof_string\":\"System.String\",\"is_car\":true,\"as_ok\":true,\"as_fail_null\":true}";
        cases.Add(MakeCase(
            "other_operators_sizeof_typeof_is_as_ternary",
            "实测 sizeof、typeof(string)、三元 ?:、is 类型判断与 as 安全引用转换",
            expectedOther,
            actualOther
        ));

        // Case 7: Operator precedence and parentheses
        int p0 = 7 + 3 * 2;
        int pa = 20, pb = 10, pc = 15, pd = 5;
        int pe1 = (pa + pb) * pc / pd;
        int pe2 = ((pa + pb) * pc) / pd;
        int pe3 = (pa + pb) * (pc / pd);
        int pe4 = pa + (pb * pc) / pd;
        int qa = 10, qb = 5, qc = 2;
        int q1 = qa + qb * qc;
        int q2 = (qa + qb) * qc;
        qa += qb * qc;
        bool la2 = true, lb2 = false, lc2 = true;
        bool lr1 = la2 || lb2 && lc2;
        bool lr2 = (la2 || lb2) && lc2;
        bool lr3 = la2 || (lb2 && lc2);
        string condRes = (10 > 5) ? "a大于b" : "a不大于b";
        string actualPrec = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"mul_first\":{0},\"grouped\":[{1},{2},{3},{4}],\"arith_assign\":[{5},{6},{7}],\"logic\":[{8},{9},{10}],\"cond\":{11}}}",
            p0, pe1, pe2, pe3, pe4, q1, q2, qa,
            lr1 ? "true" : "false", lr2 ? "true" : "false", lr3 ? "true" : "false",
            JsonEscape(condRes)
        );
        string expectedPrec = "{\"mul_first\":13,\"grouped\":[90,90,90,50],\"arith_assign\":[20,30,20],\"logic\":[true,true,true],\"cond\":\"a大于b\"}";
        cases.Add(MakeCase(
            "operator_precedence_and_parentheses",
            "实测算术/赋值/逻辑/条件运算符优先级及括号显式分组效果",
            expectedPrec,
            actualPrec
        ));

        string version = ".NET Framework " + Environment.Version.ToString() + " (csc.exe C# 5.0)";
        Console.WriteLine(string.Format(
            CultureInfo.InvariantCulture,
            "{{\"version\":{0},\"cases\":[{1}]}}",
            JsonEscape(version),
            string.Join(",", cases.ToArray())
        ));
    }
}
确认 7 组运算符用例输出全部与手工推演一致,包括短路逻辑零调用、位运算补码 ~60=-61、as 失败返回 null 及括号分组结果 90/50。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1321.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C#

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip

下载课程关联工程包:C#

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1346.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不会执行,因为 `&&` 是短路逻辑与,左侧为 `false` 时结果已确定。若确实需要不短路地同时求值两侧布尔表达式,应使用逻辑与运算符 `&`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习