C#の型変換はキャストかasの2つの方法がある
キャスト
データクラスから別のデータクラス等への明示的な変換の場合に使う
public class Minute
{
public int value;
public Minute(){}
public Minute(int minute){ value = minute; }
}
public class Hour{
public int value;
public Hour(){}
public Hour(int hour){ value = hour; }
public static explicit operator Minute(Hour hour){
return new Minute (hour.value * 60);
}
}
public class Hoge{
public void Test(){
Hour hour = new Hour(2);
Minute minute = (Minute)hour;
Console.WriteLine(hour.value); //2
Console.WriteLine(minute.value); //120
}
}
as
継承元のクラスで継承先のクラス等への暗黙的な変換の場合に使う
public class Second{
public int sec;
public Second(){}
public Second(int second){sec = second;}
}
public class Minute : Second
{
public Minute(){}
public Minute(int minute){sec = minute*60;}
public int GetMinute(){return sec/60;}
}
public class Hoge{
public void Test(){
List<Second> list = new List<Second> ();
list.Add(new Second(60));
list.Add(new Minute(10));
foreach(var hoge in list)
{
Minute minute = hoge as Minute;
if(minute != null)
Console.WriteLine(minute.GetMinute());// Minuteでnewしたものだけ呼ばれる
}
}