开发者

How to cast object to another where base is 'higher'?

There are two classes. Class B dervied from A.

class A
{  }

class B  : A
{  
    public B()
    {  

    }
    public int Number { get; private set; }
}

This gives me the error 'unable to cast from A to B'.

void Test()
{
    var a = new A();
    var b = (B)a;     // <== unable to cast.
}

How can I cast the ob开发者_如何转开发ject in variable A to class B?

Thank you.


Put simply, you can't - B is an A but A is not a B.


Your code fails because you don't have a B.

You could do it if you created a B instead of an A:

A a = new B();
B b = (B)a;

You could think of A as Animal and B as Bear.

You can always say a bear is an animal, but if all you've got is an unknown animal you can't always cast it into a bear. That works only if it actually is a bear.


You can't - A is not a B. Plain and simple.


You can't case a base class into its derived class. You can the other way around though.


You can't. What you can to is to provide a constructor in B that takes an A as argument, and create a new B instance based on that:

class B : A
{
    public B() { }

    public B(A original)
    {
        // copy values from original to this
    }

    public int Number { get; private set; }

}

Then you can do like this

A a = new A();
B b = new B(a);


You can't - a is an A, it is not a B.


Let's replace A and B to hopefully make the impossibility of this a bit clearer:

class Fruit
{ }

class Apple : Fruit
{ }

class Banana : Fruit
{ }

// If what you wanted to do were possible...
Fruit f = new Apple();

// ...then this should be possible (but how does one magically transform
// an apple into a banana?)
Banana b = (Banana)f;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜