构造函数与实例
Coddy 面向 C 开发者的 C# 课程的第 33 课,共 48 课。
在 C 中,结构体通过初始化函数进行设置,但调用者可能会忘记调用它;未初始化的自动结构体会包含垃圾值。任何能看到结构体定义的代码都可以访问它的每个成员。C# 构造函数总会在 new 创建对象时运行,未赋值的字段初始值为零或 null,而编译器会强制限制对 private 成员的访问。与 C 结构体值不同,赋值时类实例会通过引用共享,并由垃圾回收器释放。
构造函数会建立一个有效的实例。实例方法通过 this 操作该对象,字段会在多次调用之间保存对象的状态。每次更新后进行截断,与只对最终总和进行截断并不相同。将可复用的类放在与练习和启动器分开的源文件中。
C 参考
#include <stdio.h>
struct Counter { int count; };
static int clamp_zero(int n) { return n < 0 ? 0 : n; }
static void counter_init(struct Counter *c, int n) { c->count = clamp_zero(n); }
static void counter_add(struct Counter *c, int n) { c->count = clamp_zero(c->count + n); }
static int counter_value(const struct Counter *c) { return c->count; }
int main(void) {
struct Counter counter; /* 在 counter_init 运行前,值未初始化 */
counter_init(&counter, 1);
counter_add(&counter, 3);
printf("%d\n", counter_value(&counter));
return 0;
}
C# 辅助声明
class NamedItem { public string Name { get; private set; } public NamedItem(string name) { Name = name; } }Main 中的 C# 语句
var item = new NamedItem("pen");
Console.WriteLine(item.Name);这些是用于教学的重点摘录。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。
参考输出:
4C# 输出:
pen挑战
简单在 Counter.cs 中完成 Counter。将初始值设为 max(0, initial)。每次只添加一个变化量,并在每次添加后将状态限制为不低于零。公开 Value。不同实例不得共享状态。
编辑未锁定的 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 = I(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var c1 = new Counter(1); var c2 = new Counter(7); c1.Add(-5); c1.Add(2); if (c1.Value != 2 || c2.Value != 7 || new Counter(-1).Value != 0) throw new Exception("Counter API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器