问题描述
那些刚回答我的人.....如果我有正确的写完
,那真的会有所帮助。
好的我会用更好的名字来解释我的问题。
我有这个:
InterFaceClass
^
ClassA
^
^
ClassB
ClassC
所以我有一个ClassA继承的接口类。 ClassB和C然后
继承自classA。
i然后想要这样做:
ClassB myObj =( ClassB)some_ClassA_Instance;
我得到一个无效的演员。为什么?
Hi guys who just answered me.....it really would have helped if i had
written it right.
Ok i will use better names to explain my problem.
I have this:
InterFaceClass
^
ClassA
^
^
ClassB
ClassC
So i have an interface class that ClassA inherits from. ClassB and C then
inherit from classA.
i then want to do this:
ClassB myObj = (ClassB)some_ClassA_Instance;
And i get a invalid cast. Why?
推荐答案
因为some_ClassA_instance不是ClassB。
Because some_ClassA_instance is not a ClassB.
因为some_ClassA_instance不是ClassB。
Because some_ClassA_instance is not a ClassB.
如果我们使用不同的名字,也许会更清楚:
界面IAnimal //动物界面
类AnimalBase:IAnimal //动物基类
类狗:AnimalBase //狗是动物
类猫:AnimalBase //动物中的猫
AnimalBase obj = new AnimalBase(); //这是一种通用动物,
它可能是任何东西
狗myDog =(狗)obj; //尝试将通用动物施放给狗
//这是无效的,因为
动物可能不是狗
AnimalBase obj = new Dog(); //这是有效的,因为狗*是*
动物
//然而你只能
访问
//通用动物
狗myDog =(狗)obj; //现在这是有效的,因为obj是
实际上是狗
Cat myCat =(Cat)obj; //这是*无效*因为obj是
*不是*一只猫。
希望这会有所帮助。
Chris
If we use different names, maybe it will be clearer:
interface IAnimal //Animal Interface
class AnimalBase : IAnimal //Animal base class
class Dog : AnimalBase //A Dog is an animal
class Cat : AnimalBase //A Cat in an animal
AnimalBase obj = new AnimalBase(); //This is a generic animal,
it could be anything
Dog myDog = (Dog)obj; //Try to cast generic animal to Dog
//This is not valid because an
animal may not be a dog
AnimalBase obj = new Dog(); //This is valid because a Dog *is* an
Animal
//However you can only
access the properties of a
//Generic animal
Dog myDog = (Dog)obj; //This is now valid because obj is
actually a Dog
Cat myCat = (Cat)obj; //This is *invalid* because obj is
*not* a Cat.
Hope this helps a little.
Chris
这篇关于铸造问题正确的问题!抱歉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!