Menu
CoddyTech

静态成员与实例成员

Coddy 面向 C++ 开发者的 C# 课程的第 35 课,共 48 课。

C++ 静态数据和 C# 静态成员都由类型共享。在本参考示例中,C++17 的内联静态成员无需单独定义;C# 则有自己的初始化规则。即使创建计数器由多个对象共享,每个实例的值也必须保持独立。

静态成员属于类型,而不是某个实例。只有确实需要共享时,它们才适合用于共享计数器。实例字段仍然保存每个对象各自的值。显式重置可以让本练习重复运行;在无关的设计中,应避免隐藏的共享状态。

C++ 参考

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Ticket { public: inline static int created=0; int value; explicit Ticket(int n):value(n) { created++; } };
int main() {
Ticket::created=0; Ticket first(4),second(7); cout << Ticket::created << "\n";
}

C# 辅助声明

class Unit { public static string Label = "shared"; public string Name; public Unit(string name) { Name = name; } }

Main 中的 C# 语句

var a = new Unit("one");
var b = new Unit("two");
Console.WriteLine(Unit.Label + ":" + a.Name + ":" + b.Name);

这些是用于教学的重点摘录。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。

参考输出:

2

C# 输出:

shared:one:two
challenge icon

挑战

简单

完成 Ticket。每个构造函数都会将种子保存为 Value,并递增共享的 Created 计数。Reset 会将 Created 设为零。Solve 会重置计数,为每个输入创建一个 Ticket,并返回计数:值。每个实例的值必须彼此独立。

编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述的行,调用 Exercise.Solve,验证输入未被修改,并在最后输出一个换行符。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。

锁定的启动程序还会独立测试导出的辅助函数或类 API,而不只是测试 Solve 包装器。

亲手试试

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
Ticket.Reset(); var t1 = new Ticket(4); var t2 = new Ticket(9); if (Ticket.Created != 2 || t1.Value != 4 || t2.Value != 9) throw new Exception("Ticket API"); Ticket.Reset(); if (Ticket.Created != 0) throw new Exception("Reset API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 C#中的所有课

自己练习: C# 在线编译器