Menu
CoddyTech

プロパティで不変条件を守る

Coddyの「Swift開発者向けC#」コースのレッスン 34/48。

Swiftのprivate(set)プロパティは、privateセッターを持つC#プロパティに似ています。C#では、パブリックなgetterのみのアクセスと検証済みメソッドによって、呼び出し元から状態を保護します。格納プロパティと計算プロパティでは構文が異なりますが、残高に関する公開契約は同じに保つ必要があります。

プロパティは制御されたアクセスを提供し、privateフィールドは不変条件を維持します。getterは、呼び出し元が任意の値を代入できないようにしながら、状態を提示できます。private 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);

これらは要点を絞った教材用抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言と文が示されています。

参照コードの出力:

5

C#の出力:

6
challenge icon

チャレンジ

簡単

Accountを完成させましょう。初期残高は0を下回らないようにし、正の入金額は残高に加算し、0以下の入金額は無視します。残高は読み取れますが、外部から設定することはできません。

ロック解除されているC#ファイルを編集してください。表示されているロック済みのMain.csは、説明された行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを確認して、最後に改行を1つ付けて結果を出力します。宣言されているAPIを維持してください。2つ目のMainを追加したり、診断用の出力を表示したりしないでください。

ロックされたランチャーは、Solveラッパーだけでなく、エクスポートされたヘルパーまたはクラスのAPIも個別にテストします。

自分で試してみよう

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);
}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Swift開発者向けC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ