蓝色天空网mbsky.com · 知识 · 实践 · 创造C# · 本地阅读预览
教程 / 后端开发 / C#

C# 语言测验

系统梳理 C# 语言测验涵盖的 30 项核心基础考点(数据类型与字节宽度、变量声明与类型转换、入口与 I/O、OOP/接口/资源释放及控制流与异常),严守规范不执行来源脚本,改由本地 csc.exe 离线断言脚本逐项实测并订正多处题库细节。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

C# 基础知识挑战范围与安全核验原则

本章节汇总 C# 语言核心基础自测要点,全面覆盖语言定位与 `.cs` 源码扩展名、基元类型字节大小与默认值、变量声明与数值转换、程序入口 `Main` 与控制台输入输出、面向对象(类/继承/接口/命名空间/属性/`IDisposable`)以及流程控制与异常处理共 30 项考点。来源测验页依赖外部测验脚本、内联样式与页面题库脚本驱动交互界面;本站严格遵循安全规则绝不加载或执行任何来源脚本,而是静态登记全部 6 处页面嵌入元素,并将全部 30 项考点重构为独立可编译运行的本地 C# 5.0 断言实验。

30 项核心考点实测核验与易错细节订正

基元类型、声明与转换实测核验:C# 是基于 .NET 生态、支持跨平台编译的面向对象高级语言,源码文件默认扩展名为 `.cs`;`sizeof` 实测确认整型宽度严格满足 `sbyte(1) < short(2) < int(4) < long(8)`,`float` 占 `4` 字节,`char` 占 `16` 位(2 字节 UTF-16),整数默认字面量类型为 `int`(`Int32`),`bool` 默认值为 `False`,数值 `35` 在 `sbyte`(`-128..127`)范围内可紧凑存储;合法变量声明为 `int a = 32; int b = 40;`,定义编译期常量用 `const`,隐式类型局部变量用 `var`(须同时初始化)。两处高频易错勘误:第一,在 `float b = 3.5f` 与 `int` 相加转换题中,C# 区分大小写,正确类名为首字母大写的 `Convert.ToInt32(b)`(而非小写的 `convert`),且 `Convert.ToInt32(3.5f)` 按银行家舍入到偶数为 `4`(`12 + 4 = 16`),而强制截断 `(int)3.5f` 得 `3`(`12 + 3 = 15`);第二,`string` 是 `System.String` 的语言关键字别名,实测 `typeof(string) == typeof(System.String)` 为 `True`,二者指代同一类型。

入口 I/O、面向对象与控制流实测核验:标准入口方法名为 `Main`,控制台输出行与读取行分别为 `Console.WriteLine()` 与 `Console.ReadLine()`,字符串拼接常用 `+` 运算符,单行注释以 `//` 起始(块注释为 `/* ... */`);定义类用 `class`、定义接口用 `interface`、定义命名空间用 `namespace`,类继承与接口实现均统一使用冒号 `:`;定义属性使用 `get`/`set` 访问器,确定性释放非托管资源需实现 `IDisposable` 接口并配合 `using` 语句;条件判断语句包括 `if`(及 `switch`),循环语句包含 `for`、`while`、`do-while`、`foreach`(C# 不存在 `repeat` 关键字),跳出循环使用 `break`,结构化异常处理使用 `try-catch-finally`(也允许单独 `try-catch` 或 `try-finally`)。本站 5 组确定性断言已在本机 `csc.exe` 全部核验通过,可用于完成整套 C# 教程的系统复盘。

运行 csc.exe (.NET Framework 4.x) C# 30 项语言测验核心考点离线断言脚本

csharp · 阅读源码
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace CSharpQuizLab
{
    internal interface INamedEntity
    {
        string Label { get; set; }
    }

    internal class BaseEntity
    {
        public string Kind { get { return "Base"; } }
    }

    internal class DerivedEntity : BaseEntity, INamedEntity, IDisposable
    {
        public string Label { get; set; }
        public bool Disposed { get; private set; }

        public void Dispose()
        {
            Disposed = true;
        }
    }

    internal class Program
    {
        private const int MaxLimit = 100;

        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"
            );
        }

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

            // Case 1: Primitive sizes, ordering, defaults (Q1, Q2, Q4, Q5, Q7, Q8, Q9, Q10)
            int szSbyte = sizeof(sbyte);
            int szShort = sizeof(short);
            int szInt = sizeof(int);
            int szLong = sizeof(long);
            int szFloat = sizeof(float);
            int charBits = sizeof(char) * 8;
            bool sizeOrder = (szSbyte < szShort && szShort < szInt && szInt < szLong);
            bool fitsSbyte = (35 >= sbyte.MinValue && 35 <= sbyte.MaxValue);
            string defaultLitType = (35).GetType().Name;
            bool defaultBool = default(bool);
            string actual1 = string.Format(
                "long={0};float={1};charBits={2};order={3};sbyte35={4};lit={5};boolDef={6}",
                szLong, szFloat, charBits, sizeOrder, fitsSbyte, defaultLitType, defaultBool
            );
            cases.Add(CaseJson(
                "quiz_types_sizes_defaults",
                "Verify primitive sizes (long=8, float=4, char=16-bit), ordering sbyte<short<int<long, int literal default, and bool default False",
                "long=8;float=4;charBits=16;order=True;sbyte35=True;lit=Int32;boolDef=False",
                actual1
            ));

            // Case 2: Declarations, Convert.ToInt32 vs cast, const, var, string/String alias (Q3, Q6, Q15, Q16, Q17)
            int a = 32;
            int b = 40;
            float fb = 3.5f;
            int convSum = 12 + Convert.ToInt32(fb); // 12 + 4 (banker's rounding to even) = 16
            int castSum = 12 + (int)fb;             // 12 + 3 (truncation) = 15
            var inferred = "csharp";
            bool stringSameAsSystemString = (typeof(string) == typeof(System.String));
            string actual2 = string.Format(
                "ab={0}/{1};conv={2};cast={3};const={4};varType={5};strAlias={6}",
                a, b, convSum, castSum, MaxLimit, inferred.GetType().Name, stringSameAsSystemString
            );
            cases.Add(CaseJson(
                "quiz_declarations_and_conversions",
                "Verify valid variable declarations, Convert.ToInt32(3.5f) vs (int)3.5f, const, var, and string == System.String",
                "ab=32/40;conv=16;cast=15;const=100;varType=String;strAlias=True",
                actual2
            ));

            // Case 3: Entry point Main, Console IO APIs, string + concat, comments (Q11, Q12, Q13, Q14, Q28, Q29)
            MethodInfo entry = typeof(Program).GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
            bool hasWriteLine = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }) != null;
            bool hasReadLine = typeof(Console).GetMethod("ReadLine", Type.EmptyTypes) != null;
            string joined = "C#" + " " + "Quiz"; // single-line comment check
            /* multi-line comment check */
            string actual3 = string.Format(
                "entry={0};wl={1};rl={2};concat={3}",
                entry != null ? entry.Name : "", hasWriteLine, hasReadLine, joined
            );
            cases.Add(CaseJson(
                "quiz_entry_io_strings_comments",
                "Verify Main entry signature, Console.WriteLine/ReadLine reflection, + string concatenation, and comment syntax",
                "entry=Main;wl=True;rl=True;concat=C# Quiz",
                actual3
            ));

            // Case 4: OOP class/interface/namespace/:/get-set/IDisposable (Q18, Q19, Q20, Q21, Q22, Q26, Q27)
            DerivedEntity ent;
            using (ent = new DerivedEntity { Label = "demo" })
            {
                if (ent.Label != "demo") throw new InvalidOperationException();
            }
            bool oopOk = (ent is BaseEntity) && (ent is INamedEntity) && (ent is IDisposable) && ent.Disposed;
            string ns = typeof(DerivedEntity).Namespace;
            cases.Add(CaseJson(
                "quiz_oop_inheritance_interface_namespace",
                "Verify class/interface/namespace, colon inheritance/implementation, get/set property, and IDisposable via using",
                "oop=True;ns=CSharpQuizLab;kind=Base;label=demo",
                string.Format("oop={0};ns={1};kind={2};label={3}", oopOk, ns, ent.Kind, ent.Label)
            ));

            // Case 5: Control flow (if/for/while/foreach/break) & try-catch-finally (Q23, Q24, Q25, Q30)
            int sumFor = 0;
            for (int i = 1; i <= 5; i++)
            {
                if (i == 4) break;
                sumFor += i; // 1 + 2 + 3 = 6
            }
            int wCount = 0;
            while (wCount < 2) wCount++;
            int feSum = 0;
            foreach (int n in new int[] { 2, 4 }) feSum += n;
            string exFlow = "";
            try { int zero = 0; int bad = 1 / zero; Console.Write(bad); }
            catch (DivideByZeroException) { exFlow += "C"; }
            finally { exFlow += "F"; }
            cases.Add(CaseJson(
                "quiz_control_flow_and_exceptions",
                "Verify if, for+break, while, foreach loops and try-catch-finally execution flow",
                "for=6;while=2;foreach=6;ex=CF",
                string.Format("for={0};while={1};foreach={2};ex={3}", sumFor, wCount, feSum, exFlow)
            ));

            Console.WriteLine(string.Format(
                "{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
                Environment.Version.ToString(),
                string.Join(",", cases.ToArray())
            ));
        }
    }
}
预期结果 · 待实际运行核验
  • 核对基元类型字节宽度与默认值、Convert.ToInt32(3.5f)==4 与 (int)3.5f==3、string==System.String、Main/Console 反射、OOP/IDisposable 及控制流与异常处理全部通过。
运行 csc.exe (.NET Framework 4.x) C# 30 项语言测验核心考点离线断言脚本

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

当前源码 SHA256:47411621d3ec6e409623977c98f1bcc24f0d6bfe209ca20ac90a8d11cd4e85ab

下载本站示例源码

本地运行

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

下载C# 语言测验实验

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

ZIP SHA256:287912ab650a69c338820154d1ebf43e922929a546e814572fed7cf01d64e54a

常见错误与边界

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

练习与解答

在 C# 中,`Convert.ToInt32(3.5f)` 与 `(int)3.5f` 的计算结果分别是多少?为什么两者不同?

展开参考解答

`Convert.ToInt32(3.5f)` 返回 `4`,而 `(int)3.5f` 返回 `3`。因为强制类型转换 `(int)` 直接向零截断小数部分,而 `Convert.ToInt32` 执行四舍六入五成双(银行家舍入法),将 `3.5` 舍入到最接近的偶数 `4`。

规范与官方依据