属性保护不变量
Coddy 面向 Kotlin 开发者的 C# 课程的第 34 课,共 48 课。
Kotlin 属性和 C# 属性都支持受控访问。Kotlin 的 private set 类似于带有私有 setter 的 C# 属性。只读的公共接口加上经过验证的方法,可以防止调用方赋予余额无效值。
属性提供受控访问,而私有字段可以维护不变量。getter 可以呈现状态,而不允许调用方赋予任意值。使用私有 setter 或只读属性是一种接口设计选择;如果更新需要验证,就不要公开可变字段。
Kotlin 参考
class Wallet(opening:Int){var balance=opening
private set}
fun main() {
val wallet=Wallet(5)
println(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:开户余额会被限制为不低于零,正数存款会增加余额,零或负数存款会被忽略。余额可读取,但不能通过公共方式设置。
编辑未锁定的 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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器