抽象クラス
Coddyの「C言語開発者のためのC#」コースのレッスン 39/48。
Cには抽象クラスがありません。形状の契約は関数ポインターを持つ構造体であり、コードでstruct Shapeを宣言し、そのareaポインターをNULLにすることを妨げるものはありません。それを呼び出すと未定義動作になります。C#の抽象クラスはnewで作成できず、抽象メソッドには本体がありません。また、オーバーライドを忘れた具象クラスはコンパイラーによって拒否されます。ガベージコレクターがオブジェクトを回収するため、基底ポインターを通じて正しくfreeする必要はありません。
抽象クラスは共通の構造を定義し、派生クラスに動作の実装を要求できます。直接インスタンス化することはできません。基底クラスの抽象メソッドには本体がなく、派生した具象クラスはそれらをオーバーライドする必要があります。ポリモーフィックなコレクションを使えば、呼び出し側は具象クラスの型を一つずつ調べずに面積を求められます。
Cの参照例
#include <stdio.h>
struct Shape {
double (*area)(const struct Shape *self);
};
struct Triangle {
struct Shape shape; /* 最初のメンバーなので、Triangle を Shape として使用できる */
int b, h;
};
static double triangle_area(const struct Shape *self) {
const struct Triangle *t = (const struct Triangle *)self;
return t->b * t->h / 2.0;
}
int main(void) {
struct Triangle triangle = { { triangle_area }, 3, 2 };
struct Shape *shape = &triangle.shape;
printf("%.1f\n", shape->area(shape));
return 0;
}
C#の関連する宣言
abstract class Named { public abstract string Describe(); }
class NamedCode : Named { private string code; public NamedCode(string code) { this.code = code; } public override string Describe() { return "code:" + code; } }Main内のC#の文
Named item = new NamedCode("A");
Console.WriteLine(item.Describe());これらは学習に焦点を当てた抜粋です。課題のファイルには実行可能な完全版のラッパーが含まれています。上記のスニペットは、関連する宣言と文を示しています。
参照出力:
3.0C#の出力:
code:Aチャレンジ
簡単抽象クラス Shape を継承する Rectangle と Triangle を実装してください。Rectangle の面積は width * height です。Triangle の面積は base * altitude / 2.0 です。Shape 参照を通じて合計を返してください。寸法は 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 = I(input[1]); string before1=Snapshot(a1);
var a2 = I(input[2]); string before2=Snapshot(a2);
var a3 = I(input[3]); string before3=Snapshot(a3);
Shape sh1 = new Rectangle(2,3); Shape sh2 = new Triangle(1,1); if (sh1.Area() != 6 || sh2.Area() != 0.5) throw new Exception("Shape API");
var result = Exercise.Solve(a0,a1,a2,a3);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
if (Snapshot(a3) != before3) throw new Exception("Input mutation");
Console.WriteLine(result.ToString("0.0", CultureInfo.InvariantCulture));
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C言語開発者のためのC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ