4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

キャストとas

Posted at

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したものだけ呼ばれる
	}
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?