1.父類不能直接強制轉換成子類
2.子類可以強制轉換成父類,但是在父類中只能取父類的字段與方法
因此在一個父類對應多個子類的時候,不知道具體是哪個子類的時候,就可以先聲明一個父類的類型。(如例1)
3.由1,2知,父類不能直接強制轉換成子類,但是可以通過間接的方法進行轉換,例1中有所體現:將子類裝箱成父類,然后再把父類拆箱成子類,如例2。
特別說明:雖然可以通過間接方式將父類轉成子類,但實際用處不大,因為需要一個臨時的子類來進行轉換,因為其實可以直接在子類直接轉換,所以
實際用處不大。
例1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//markton 130809
namespace testApplication
{
class Program
{
static void Main(string[] args)
{
//不知道具體是哪個子類,因此先用父類來聲明
List<CParent> sL = new List<CParent>();
CSon cs1 = new CSon(); cs1.b = -1;
CSon cs2 = new CSon(); cs2.b = -2;
sL.Add(cs1); //子類可以強制轉換成父類,即裝箱
sL.Add(cs2);
for (int i = 0; i < 2;i++ )
{
//這里需要把父類再強制轉換成子類(因為是裝箱而來的父類,可以對其進行拆箱成子類)
//取出子類中的字段,即拆箱
Console.WriteLine(((CSon)sL[i]).b);
}
Console.ReadLine();
}
}
public class CParent
{
public int a=0;
}
public class CSon:CParent
{
public int b=0;
public int run()
{
return a + b;
}
}
public class CSon2 : CParent
{
public string c = "CSon2";
public int run()
{
return a;
}
}
}
例2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//markton 130809
namespace testApplication
{
class Program
{
static void Main(string[] args)
{
CParent Cpa = new CParent();
Cpa.a=9;
//設置一個臨時的子類
CSon tmpt = new CSon();
tmpt.a = 9;
//進行裝箱
Cpa = (CParent)tmpt;
//進行拆箱
CSon cson = (CSon)Cpa;
Console.WriteLine(cson.a);
Console.ReadLine();
}
}
public class CParent
{
public int a=0;
}
public class CSon:CParent
{
public int b=0;
public int run()
{
return a + b;
}
}
public class CSon2 : CParent
{
public string c = "CSon2";
public int run()
{
return a;
}
}
}
