Nullable値とデフォルト値
Coddyの「C++開発者のためのC#」コースのレッスン 11/48。
C++のoptional<int>はC#のint?を理解するための有用な参考例であり、この仕様ではvalue_orが??に対応します。どちらも0を値がないものとして扱うべきではありません。この古いコンパイラーでは、C#の参照型のnull許容性は、null許容値型とは別の問題です。
intにはnullを格納できません。int?はNullable<int>です。HasValue、Value、??を使うと、値がない状態を明示できます。null合体演算子は、値がnullの場合にのみ代替値を選びます。これは古いコンパイラーでサポートされているnull許容値型の構文であり、最新のnull許容参照型の解析ではありません。
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;
int main() {
optional<int> count=0;
cout << count.value_or(9) << "\n";
}
Main内のC#文
int? count = 0;
Console.WriteLine(count ?? 9);これらは要点に絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットでは関連する宣言と文を示しています。
参照出力:
0C#の出力:
0チャレンジ
簡単1行目はnullまたは整数、2行目はフォールバック値です。nullでない限り、指定されたcountを返してください。0と負の値もそのまま扱ってください。
ロックされていないC#ファイルを編集してください。ロックされているMain.csには、説明された行を読み取り、Exercise.Solveを呼び出し、入力が変更されていないことを検証して、最後に改行を1つ付けて結果を出力するコードがあります。宣言済みのAPIを維持してください。2つ目のMainを追加したり、診断出力を表示したりしないでください。
自分で試してみよう
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 = input[0] == "null" ? (int?)null : I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
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);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのC#のすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ