前提
"動物クラス" と "動物クラスを継承している人間クラス" があり、
"動物クラス" には、名前プロパティと年齢プロパティが定義され、
"人間クラス" には、国籍プロパティが定義されています。
現象
まず、以下の手順で処理を行ないます。
①人間クラスのインスタンスを作り、名前、年齢、国籍を代入する。
②この人間クラスのインスタンスを動物クラスのインスタンスにキャストする。(ダウンキャスト)
③さらに、この動物クラスのインスタンスを人間クラスのインスタンスにキャストする。(アップキャスト)
※詳しくは、下記ソースコードをご参照ください。
すると、人間クラスのインスタンスの国籍プロパティに①で代入した国籍が格納されます。
聞きたい事
動物クラスのインスタンスにキャストしたときに国籍プロパティの値が欠落して、最終的に国籍プロパティが空になると思ったのですが、何故、値が格納されているのでしょうか?
よろしくお願いします。
ソースコード
using System; using System.Diagnostics; using System.Windows.Forms; namespace ダウンキャストテスト { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// Animalクラス /// </summary> private class Animal { /// <summary> /// 名前プロパティ /// </summary> public string Name { get; set; } /// <summary> /// 年齢プロパティ /// </summary> public int Age { get; set; } /// <summary> /// コンストラクタ /// </summary> public Animal(string name, int age) { this.Name = name; this.Age = age; } } /// <summary> /// Humanクラス /// </summary> private class Human : Animal { /// <summary> /// 国籍プロパティ /// </summary> public string Nationality { get; set; } /// <summary> /// コンストラクタ /// </summary> /// <param name="name"></param> /// <param name="age"></param> /// <param name="nationality"></param> public Human(string name, int age, string nationality) : base(name, age) { Nationality = nationality; } } private void Button1_Click(object sender, EventArgs e) { //Humanクラスのインスタンスを作成 Human h1 = new Human("Taro", 3, "Japan"); Debug.WriteLine(string.Format("---(1)--- Name:{0}, Age:{1}, Nationality:{2}", h1.Name, h1.Age, h1.Nationality)); //Human型の変数 h1 をAnimal型の変数 a1 にキャスト Animal a1 = new Animal("---", 0); a1 = h1 as Animal; Debug.WriteLine(string.Format("---(2)--- Name:{0}, Age:{1}", a1.Name, a1.Age)); //Animal型の変数aをHuman型の変数h2にキャスト Human h2 = new Human( "---", 0, "---"); h2 = a1 as Human; Debug.WriteLine(string.Format("---(3)--- Name:{0}, Age:{1}, Nationality:{2}", h2.Name, h2.Age, h2.Nationality)); } } }
実行結果
---(1)--- Name:Taro, Age:3, Nationality:Japan ---(2)--- Name:Taro, Age:3 ---(3)--- Name:Taro, Age:3, Nationality:Japan
環境
Microsoft Windows 10 Pro (Version 1809)
Microsoft Visual Studio Community 2017(Version 15.9.4)
Microsoft .NET Framework(Version 4.7.03190)
回答2件
あなたの回答
tips
プレビュー