属性保护不变式
Coddy 面向 Swift 开发者的 C# 课程的第 34 课,共 48 课。
Swift 的 private(set) 属性类似于带有私有 setter 的 C# 属性。C# 中仅允许公开读取,再通过经过验证的方法保护状态不受调用方影响。存储属性和计算属性的语法有所不同,但可观察到的余额契约应保持一致。
属性提供受控访问,同时由私有字段维护不变量。getter 可以呈现状态,但不允许调用方随意赋值。使用私有 setter 或仅 getter 的属性是一种契约选择;如果更新需要验证,就不要公开可变字段。
Swift 参考代码
import Foundation
class Wallet{private(set) var balance:Int;init(_ opening:Int){balance=opening}}
let wallet=Wallet(5)
print(wallet.balance)C# 支持性声明
class Reading { private int raw; public Reading(int raw) { this.raw = raw; } public int Doubled { get { return raw * 2; } } }Main 中的 C# 语句
var reading = new Reading(3);
Console.WriteLine(reading.Doubled);这些是用于重点讲解的代码片段。挑战文件中包含完整的可执行包装代码;以上片段展示了相关的声明和语句。
参考输出:
5C# 输出:
6挑战
简单完成 Account:开户余额会被限制为至少为 0,正数存款会增加余额,零或负数存款会被忽略。余额可以读取,但不能通过公开方式设置。
编辑未锁定的 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 accountOne = new Account(-2); var accountTwo = new Account(5); accountOne.Deposit(3); accountOne.Deposit(-9); if (accountOne.Balance != 3 || accountTwo.Balance != 5) throw new Exception("Account 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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Swift 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器