Menu
CoddyTech

静的メンバーとインスタンスメンバー

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

C++の静的データとC#の静的メンバーは、どちらも型によって共有されます。この参考例では、C++17のインライン静的メンバーを使うことで個別の定義が不要です。C#には独自の初期化規則があります。作成カウンターを共有している間も、インスタンスの値はそれぞれ独立していなければなりません。

静的メンバーはインスタンスではなく型に属します。意図的に共有する場合に限り、共有カウンターに適しています。インスタンスフィールドには、引き続き各オブジェクトの値が保持されます。明示的にリセットすることで、この演習を繰り返し実行できます。無関係な設計では、隠れた共有状態を避けましょう。

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 Ticket { public: inline static int created=0; int value; explicit Ticket(int n):value(n) { created++; } };
int main() {
Ticket::created=0; Ticket first(4),second(7); cout << Ticket::created << "\n";
}

C#の補助宣言

class Unit { public static string Label = "shared"; public string Name; public Unit(string name) { Name = name; } }

Main内のC#ステートメント

var a = new Unit("one");
var b = new Unit("two");
Console.WriteLine(Unit.Label + ":" + a.Name + ":" + b.Name);

これらは、特定の概念に焦点を当てた教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれています。上記のスニペットは、関連する宣言とステートメントを示しています。

参考出力:

2

C#の出力:

shared:one:two
challenge icon

チャレンジ

簡単

Ticketを完成させましょう。各コンストラクターは、シードをValueとして保存し、共有のCreatedカウントを増やします。ResetはCreatedをゼロに設定します。Solveはリセットし、入力ごとに1つのチケットを作成して、カウント:値を返します。インスタンスの値はそれぞれ独立していなければなりません。

ロックされていない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 = Ints(input[0]); string before0=Snapshot(a0);
Ticket.Reset(); var t1 = new Ticket(4); var t2 = new Ticket(9); if (Ticket.Created != 2 || t1.Value != 4 || t2.Value != 9) throw new Exception("Ticket API"); Ticket.Reset(); if (Ticket.Created != 0) throw new Exception("Reset API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon腕試し

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

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

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