蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

CSHARPWindows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。ExploreOperators.cs
ExploreOperators.cs274 行
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())
        ));
    }
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

入口文件:projects/csharp-operators-lab/ExploreOperators.cs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreOperators.cs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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