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

在本地 csc4 实测结构体无 new 初始化、Struct/Class 值与引用差异及方法/接口封装

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

namespace CSharpStructLab
{
    internal interface IDescribable
    {
        string Describe();
    }

    internal struct PublicBooks
    {
        public string title;
        public string author;
        public string subject;
        public int book_id;
    }

    internal struct EncapsulatedBooks : IDescribable
    {
        private string title;
        private string author;
        private string subject;
        private int book_id;

        public void SetValues(string t, string a, string s, int id)
        {
            title = t;
            author = a;
            subject = s;
            book_id = id;
        }

        public string Describe()
        {
            return string.Format("{0}|{1}|{2}|{3}", title, author, subject, book_id);
        }
    }

    internal struct MyStruct
    {
        public int X;
        public int Y;

        public MyStruct(int x, int y)
        {
            X = x;
            Y = y;
        }
    }

    internal class MyClass
    {
        public int X;
        public int Y;

        public MyClass()
        {
        }

        public MyClass(int x, int y)
        {
            X = x;
            Y = y;
        }
    }

    internal class Program
    {
        private static void MutateStructByValue(MyStruct s)
        {
            s.X = 999;
        }

        private static void MutateClassByRefCopy(MyClass c)
        {
            c.X = 888;
        }

        private static string Esc(string s)
        {
            if (s == null) return "null";
            StringBuilder sb = new StringBuilder("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\\': sb.Append("\\\\"); break;
                    case '"': sb.Append("\\\""); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    default:
                        if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
                        else sb.Append(c);
                        break;
                }
            }
            sb.Append("\"");
            return sb.ToString();
        }

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

        private static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            List<string> cases = new List<string>();

            // Case 1: Struct declaration & instantiation without new
            PublicBooks book1;
            PublicBooks book2;
            book1.title = "C Programming";
            book1.author = "Nuha Ali";
            book1.subject = "C Programming Tutorial";
            book1.book_id = 6495407;
            book2.title = "Telecom Billing";
            book2.author = "Zara Ali";
            book2.subject = "Telecom Billing Tutorial";
            book2.book_id = 6495700;
            string actual1 = string.Format(
                "b1={0}/{1},b2={2}/{3}",
                book1.title, book1.book_id, book2.title, book2.book_id
            );
            cases.Add(CaseJson(
                "struct_without_new_init",
                "验证不使用 new 声明结构体变量并逐字段赋值后读取记录",
                "b1=C Programming/6495407,b2=Telecom Billing/6495700",
                actual1
            ));

            // Case 2: Struct vs Class value copy vs reference copy & parameter passing
            MyStruct st1 = new MyStruct(1, 2);
            MyStruct st2 = st1;
            st1.X = 5;
            MutateStructByValue(st2);

            MyClass cl1 = new MyClass(3, 4);
            MyClass cl2 = cl1;
            cl1.X = 6;
            MutateClassByRefCopy(cl2);

            MyStruct? nullableSt = null;
            MyClass nullCl = null;
            string actual2 = string.Format(
                "st={0}/{1},cl={2}/{3},stNull={4},clNull={5},isVal={6}",
                st1.X, st2.X, cl1.X, cl2.X, !nullableSt.HasValue, nullCl == null, typeof(MyStruct).IsValueType
            );
            cases.Add(CaseJson(
                "struct_vs_class_semantics",
                "对比结构体值拷贝/按值传参/可空包装与类引用共享/默认可空语义",
                "st=5/1,cl=888/888,stNull=True,clNull=True,isVal=True",
                actual2
            ));

            // Case 3: Struct with private fields, methods, new() and interface implementation
            EncapsulatedBooks eb1 = new EncapsulatedBooks();
            EncapsulatedBooks eb2 = new EncapsulatedBooks();
            eb1.SetValues("C Programming", "Nuha Ali", "C Programming Tutorial", 6495407);
            eb2.SetValues("Telecom Billing", "Zara Ali", "Telecom Billing Tutorial", 6495700);
            IDescribable asIface = eb1;
            string actual3 = string.Format("eb1={0};eb2={1}", asIface.Describe(), eb2.Describe());
            cases.Add(CaseJson(
                "struct_methods_and_interface",
                "验证结构体封装私有字段、通过 new() 调用方法并实现 IDescribable 接口",
                "eb1=C Programming|Nuha Ali|C Programming Tutorial|6495407;eb2=Telecom Billing|Zara Ali|Telecom Billing Tutorial|6495700",
                actual3
            ));

            Console.WriteLine(string.Format(
                "{{\"version\":{0},\"cases\":[{1}]}}",
                Esc("CLR " + Environment.Version.ToString()),
                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-struct-lab/ExploreStruct.cs

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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