【メモ】『C#大学チュートリアル』-第10章オブジェクト向けプログラミング:多態性


1.タイプ変換:
ParentClass a = new ChildClass();
ChildClass c = (ChildClass) a;
ParenClass b = new ParentClass();
//false
b is ChildClass;

2.抽象クラスと抽象メソッドを定義します.
(1).抽象クラスでのみ抽象メソッドを定義できます.
(2).抽象クラスをインスタンス化できません.
(3).抽象的な方法はサブクラスで上書きされなければならない.
(4).抽象クラスで虚関数(クラスに上書きされる必要がないvirtual関数)を定義できます.
public abstract class Shape
{
    public virtual double Area()
    {
        return 0;
    }

    public virtual double Volume()
    {
        return 0;
    }

    public abstract double Func();

    public abstract string Name
    {
        get;
    }
}

3.インタフェースの定義:
(1). インタフェースには構造関数が含まれず、方法には実装が含まれていない.
(2). インタフェースのすべての属性と方法はクラス実装で定義されなければならない.
(3). インタフェースはpublicとしてのみ宣言できます.
public interface IShape
{
    double Area();
    double Volume();
    string Name { get; }
}
public class Point:IShape
{
    public Point ()
    {
    }
    
    public virtual double Area()
    {
        return 0;
    }
    
    public virtual double Volume()
    {
        return 0;
    }
    
    public virtual string Name
    {
        get
        {
            return "Point";
        }
    }
}

4.依頼:
C#はメソッド参照をパラメータとして許可せず、1つの作成依頼によって作成します.
namespace TestDelegate
{
    class Program
    {
        private delegate bool Comparator(int a, int b);

        private static void Func(Comparator Comp)
        {
            MessageBox.Show(Comp(1,2).ToString());
        }

        private static bool Compare(int a, int b)
        {
            return a < b;
        }

        static void Main(string[] args)
        {
            Func(new Comparator(Compare));
        }
    }
}

5.リロード演算子:
public static ComplexNumber operator + ( ComplexNumber x, ComplexNumber y )
{
    return new ComplexNumber( x.Real + y.Real, x.Imaginary + y.Imaginary);
}