C#のis-asとかキャスト

やるべきことのモチベーションを上げるためにC#に現実逃避

is演算子はa is bのように使い、キャスト可能であればtrueを、否であればfalseを返す。

if(a is B)

のように使う。
asは、キャスト時に使う。asを使ったキャストは失敗するときは例外を吐くんじゃなくてnullになる。

Hoge b = a as Hoge;

if(b != null)
{
  //hogehoge
}

ボックス化とは値型のデータを参照型にキャストすること。これにはasはつかえない。

データ型の返還メソッドを自分で定義するにはimplicit,explicit operetorを使う。

 class Centi
    {
        public double length {get; set;}
        public static explicit operator Metor(Centi c)
        {
            return new Metor() { length = c.length / 10 };
        }
    }

    class Metor
    {
        public double length { get; set; }
        public static implicit operator Centi(Metor m)
        {
            return new Centi() { length = m.length * 10 };
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
     
        
        private void button1_Click(object sender, EventArgs e)
        {
            Metor m = new Metor() { length = 98};
            Centi c = m;
            Console.WriteLine(c.length);
            m = (Metor)c;
            Console.WriteLine(m.length);
            
        }
    }