キャストと型変換は、式をあるデータ型から別のデータ型に変える、異なる方法です。
式は、キャスト演算子(<type>)を使って別の型にキャストできます。
long l = 1000L;
int i = (int)l;
object o = new Random();
Random r = (Random)o;
型に互換性がない場合は、InvalidCastExceptionのインスタンスがスローされます。数値の場合は、受け取る側の型がキャストする値を表現できないことを意味します。クラスの場合は、どちらか一方の型がもう一方から派生している必要があります(これは構造体にもそのまま当てはまります)。
_キャスト_に代わる方法は、is演算子を使った_型変換_です。これは通常、参照型とnull許容型に適用されます。
object o = new Random();
if (o is Random rand)
{
int ii = rand.Next();
// now, do something random
}
オブジェクトの正確な型を調べる必要がある場合、isは少し寛容すぎるかもしれません。isは、あるクラスと、そのクラスから直接的または間接的に派生したすべてのクラスやインターフェースに対してtrueを返すからです。そのような場合は、typeofとObject.GetType()が解決策です。
object o = new List<int>();
o is ICollection<int> // true
o.GetType() == typeof(ICollection<int>) // false
o is List<int> // true
o.GetType() == typeof(List<int>) // true
サッカークラブのfootball-match-reportsはリーグで快進撃を続けていて、今回はセキュリティパスの印刷システムの仕事を任されました。
裏方スタッフのクラス階層は次のとおりです
TeamSupport (interface)
├ Chairman
├ Manager
└ Staff (abstract)
├ Physio
├ OffensiveCoach
├ GoalKeepingCoach
└ Security
├ SecurityJunior
├ SecurityIntern
└ PoliceLiaison
階層の完全な実装は、この演習のソースコードの一部として提供されています。
セキュリティパス作成機に渡されるデータはすべて検証済みで、nullではないことが保証されています。
SecurityPassMaker.GetDisplayName()メソッドを実装してください。Staffから派生したすべてのクラスのインスタンスでは、Titleフィールドの値を返し、それ以外の場合は"Too Important for a Security Pass"を返す必要があります。
var spm = new SecurityPassMaker();
spm.GetDisplayName(new Manager());
// => "Too Important for a Security Pass"
spm.GetDisplayName(new Physio());
// => "The Physio"
SecurityPassMaker.GetDisplayName()メソッドを変更してください。タスク1と同じ動作ですが、スタッフがセキュリティチームのメンバー(Security型またはその派生型のいずれか)である場合は、タイトルの後に" Priority Personnel"というテキストを表示する必要があります。
var spm = new SecurityPassMaker();
spm.GetDisplayName(new Physio());
// => "The Physio"
var spm2 = new SecurityPassMaker();
spm2.GetDisplayName(new Security());
// => "Security Team Member Priority Personnel"
spm2.GetDisplayName(new SecurityJunior());
// => "Security Junior Priority Personnel"
SecurityPassMaker.GetDisplayName()メソッドを変更してください。タスク2と同じ動作ですが、SecurityJunior、SecurityIntern、PoliceLiaison型のインスタンスには" Priority Personnel"というテキストを表示しないでください。
var spm2 = new SecurityPassMaker();
spm2.GetDisplayName(new Security());
// => "Security Team Member Priority Personnel"
spm2.GetDisplayName(new SecurityJunior());
// => "Security Junior"