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

实测 13 种值类型 sizeof/范围、引用别名、object 装箱拆箱、dynamic 与逐字字符串

CSHARPWindows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。ExploreDataTypes.cs
ExploreDataTypes.cs195 行
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;

public class ExploreDataTypes
{
    private class BoxRef
    {
        public int Value;
    }

    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: sizeof and default/range verification for all 13 built-in value types
        bool rangesOk = (byte.MinValue == 0 && byte.MaxValue == 255)
            && (sbyte.MinValue == -128 && sbyte.MaxValue == 127)
            && (short.MinValue == -32768 && short.MaxValue == 32767)
            && (ushort.MinValue == 0 && ushort.MaxValue == 65535)
            && (int.MinValue == -2147483648 && int.MaxValue == 2147483647)
            && (uint.MinValue == 0 && uint.MaxValue == 4294967295U)
            && (long.MinValue == -9223372036854775808L && long.MaxValue == 9223372036854775807L)
            && (ulong.MinValue == 0UL && ulong.MaxValue == 18446744073709551615UL)
            && (default(bool) == false && default(char) == '\0' && default(decimal) == 0.0m && default(double) == 0.0d && default(float) == 0.0f);
        string actualSizes = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"bool\":{0},\"byte\":{1},\"sbyte\":{2},\"char\":{3},\"short\":{4},\"ushort\":{5},\"int\":{6},\"uint\":{7},\"float\":{8},\"long\":{9},\"ulong\":{10},\"double\":{11},\"decimal\":{12},\"ranges_and_defaults_ok\":{13}}}",
            sizeof(bool), sizeof(byte), sizeof(sbyte), sizeof(char),
            sizeof(short), sizeof(ushort), sizeof(int), sizeof(uint),
            sizeof(float), sizeof(long), sizeof(ulong), sizeof(double),
            sizeof(decimal), rangesOk ? "true" : "false"
        );
        string expectedSizes = "{\"bool\":1,\"byte\":1,\"sbyte\":1,\"char\":2,\"short\":2,\"ushort\":2,\"int\":4,\"uint\":4,\"float\":4,\"long\":8,\"ulong\":8,\"double\":8,\"decimal\":16,\"ranges_and_defaults_ok\":true}";
        cases.Add(MakeCase(
            "value_types_sizeof_and_ranges",
            "实测 13 种内置值类型的 sizeof 字节尺寸、数值边界与默认值",
            expectedSizes,
            actualSizes
        ));

        // Case 2: Reference type aliasing vs value type copy
        int v1 = 10;
        int v2 = v1;
        v2 = 20;
        BoxRef r1 = new BoxRef();
        r1.Value = 10;
        BoxRef r2 = r1;
        r2.Value = 99;
        string actualRef = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"val_original\":{0},\"ref_original\":{1},\"same_ref\":{2}}}",
            v1,
            r1.Value,
            object.ReferenceEquals(r1, r2) ? "true" : "false"
        );
        string expectedRef = "{\"val_original\":10,\"ref_original\":99,\"same_ref\":true}";
        cases.Add(MakeCase(
            "reference_type_aliasing",
            "对比值类型独立拷贝与引用类型共享同一内存位置的变化同步",
            expectedRef,
            actualRef
        ));

        // Case 3: object boxing and unboxing
        object obj = 100; // 装箱
        int unboxed = (int)obj; // 拆箱
        bool wrongUnboxThrew = false;
        try
        {
            double bad = (double)obj;
            if (bad > 0) wrongUnboxThrew = false;
        }
        catch (InvalidCastException)
        {
            wrongUnboxThrew = true;
        }
        string actualBox = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"boxed_type\":{0},\"unboxed\":{1},\"wrong_unbox_invalid_cast\":{2}}}",
            JsonEscape(obj.GetType().FullName),
            unboxed,
            wrongUnboxThrew ? "true" : "false"
        );
        string expectedBox = "{\"boxed_type\":\"System.Int32\",\"unboxed\":100,\"wrong_unbox_invalid_cast\":true}";
        cases.Add(MakeCase(
            "object_boxing_and_unboxing",
            "实测 int 装箱为 System.Object、拆箱还原以及错误类型拆箱触发 InvalidCastException",
            expectedBox,
            actualBox
        ));

        // Case 4: dynamic runtime type resolution
        dynamic d = 20;
        int dInt = d + 5;
        d = "mbsky";
        int dLen = d.Length;
        string actualDyn = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"int_add\":{0},\"str_len\":{1},\"runtime_type\":{2}}}",
            dInt,
            dLen,
            JsonEscape(((object)d).GetType().FullName)
        );
        string expectedDyn = "{\"int_add\":25,\"str_len\":5,\"runtime_type\":\"System.String\"}";
        cases.Add(MakeCase(
            "dynamic_runtime_binding",
            "实测 dynamic 变量在运行时先后绑定整数运算与字符串 Length 属性",
            expectedDyn,
            actualDyn
        ));

        // Case 5: String and verbatim @ string literals
        string quoted = "C:\\Windows";
        string verbatim = @"C:\Windows";
        string multiline = @"<tag attr=""ok"">
    line2
</tag>";
        bool hasNewline = multiline.IndexOf('\n') >= 0;
        bool hasDoubleQuote = multiline.IndexOf("\"ok\"") >= 0;
        string actualStr = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"path_equal\":{0},\"path_len\":{1},\"multiline_has_nl\":{2},\"multiline_has_quote\":{3},\"is_system_string\":{4}}}",
            string.Equals(quoted, verbatim, StringComparison.Ordinal) ? "true" : "false",
            verbatim.Length,
            hasNewline ? "true" : "false",
            hasDoubleQuote ? "true" : "false",
            (typeof(string) == typeof(System.String)) ? "true" : "false"
        );
        string expectedStr = "{\"path_equal\":true,\"path_len\":10,\"multiline_has_nl\":true,\"multiline_has_quote\":true,\"is_system_string\":true}";
        cases.Add(MakeCase(
            "string_and_verbatim_literals",
            "验证普通字符串、@ 逐字路径字符串等价性、双引号转义及多行换行长度计入",
            expectedStr,
            actualStr
        ));

        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-data-types-lab/ExploreDataTypes.cs

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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