使用基类作为运行时类型c#的虚方法时出现无效的强制转换异常

时间:2016-03-05 09:50:11

标签: c# polymorphism

我知道这不是什么新鲜事,我只想知道为什么抛出InvalidCastException,因为这里的运行时类型(A是基类)有一个该方法的实现,谢谢。

class Program
{
    static void Main(string[] args)
    {
        B b = (B)new A();
        Console.WriteLine(b.Foo());
        Console.ReadLine();
    }
}

class A
{
    public virtual string Foo() => "Hello from base class";
}

class B : A
{
    public override string Foo() => "Hello from sub class";
}

2 个答案:

答案 0 :(得分:0)

仅仅因为Select tblQuickRegister.memberId , tblUserLogin.lastLogin , tblQuickRegister.dob,tblPhysicalAttributes.height, tblHomeTruth.religion, tblEducation.highestQualification , tblOccupation.occupation, tblPicture.profilePic1 from tblQuickRegister full outer join tblUserLogin on tblQuickRegister.memberId = tblUserLogin.memberId full outer join tblPhysicalAttributes on tblQuickRegister.memberId = tblPhysicalAttributes.memberId full outer join tblHomeTruth on tblQuickRegister.memberId = tblHomeTruth.memberId full outer join tblEducation on tblQuickRegister.memberId = tblEducation.memberId full outer join tblOccupation on tblQuickRegister.memberId = tblOccupation.memberId full outer join tblPicture on tblQuickRegister.memberId = tblPicture.memberId full outer join tblMaritalStatus on tblQuickRegister.memberId = tblMaritalStatus.memberId full outer join tblContact on tblQuickRegister.memberId = tblContact.memberId where tblQuickRegister.sex = @sex And tblMaritalStatus.maritalStatus = @maritalStatus And (DATEDIFF(DAY,Convert(date,tblQuickRegister.dob),getdate())/365 >= @minage) And (DATEDIFF(DAY,Convert(date,tblQuickRegister.dob),getdate())/365 <= @maxage) And tblContact.[state] = @state And tblContact.city = @city A的基类,所以B不是A。它是B B。{/ p>

例如,你是你父亲和你母亲的混合体,但你不是你的父亲或母亲。如果警察让你弄错了你的车,警察会问你爸爸或妈妈的驾驶执照吗?

您可以将 police 与编译器进行比较。编译器不接受您在类型为A的引用中设置A的实例,因为它们的类型不同。

编译器可以接受的是B上传到B的实例可以设置为A的引用:

A

答案 1 :(得分:0)

您无法将基类转换为派生类。 B可能会声明M1中不存在的某个新成员(例如方法A)。如果可以投射,如果你为M1调用A方法,它就会缺席。所以运行时会阻止这样的转换。