Menu
CoddyTech

コンストラクタとインスタンス

Coddyの「C++開発者のためのC#」コースのレッスン 33/48。

C++のコンストラクターとプライベート状態にはなじみがあるでしょう。しかし、C#では通常の変数代入によってクラスのインスタンスがコピーされるのではなく、参照されます。C#のメモリ所有権は、スタック上のオブジェクトや手動のメモリ確保とは異なりますが、インスタンスごとの不変条件を設計することは引き続き重要です。

コンストラクターは有効なインスタンスを確立します。インスタンスメソッドはthisを通じてそのオブジェクトを操作し、フィールドは呼び出しをまたいでその状態を保持します。更新のたびに値を制限することと、最終的な合計だけを制限することは異なります。再利用可能なクラスは、演習や起動プログラムとは別のソースファイルに配置しましょう。

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 Counter { int count; public: explicit Counter(int n):count(max(0,n)) {} void add(int n) { count=max(0,count+n); } int value() const { return count; } };
int main() {
Counter counter(1); counter.add(3); cout << counter.value() << "\n";
}

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);

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

参照出力:

4

C#の出力:

pen
challenge icon

チャレンジ

簡単

Counter.cs で Counter を完成させます。max(0, initial) で初期化します。変更を一つずつ加え、加算するたびに状態を 0 以上にクランプします。Value を公開します。別々のインスタンスで状態を共有してはいけません。

ロック解除された C# ファイルを編集します。表示されているロック済みの Main.cs は説明された行を読み取り、Exercise.Solve を呼び出し、入力が変更されていないことを検証して、最後に改行を一つ付けて結果を出力します。宣言済みの 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 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);
}
}
quiz icon腕試し

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

C++開発者のためのC#のすべてのレッスン

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