"DBC User" <db*****@gmail.coma écrit dans le message de news:
11**********************@i42g2000cwa.googlegroups. com...
|I have 2 classes which are exactly same except the name. I do not have
| access to either of the class to change anything in it.
| In my code, I need to copy one of one class to another class. How can I
| do this?
| class A
| {
| ...
| }
|
| class B
| {
| ....Exactly same as A, all properties and methods
| }
|
| class C
| {
| A a;
| B b;
| b = (B)a; // trying to do this but fails with invalid casting.
| }
Do you want B to behave exactly like A, or do you want to add more behaviour
to B as well as that from A ?
If you want exactly the same behaviour, then you do not need another class.
If you want B to have additional behaviour and to be assignable to a
variable of type A, then you need to use inheritance.
class A
{
...
}
class B : A
{
....Exactly same as A, all properties and methods
}
class C
{
A a;
B b;
b = (B)a; // this will still fail
}
You cannot assign an instance of one class unless they are related by
inheritance, and even then, you cannot cast an instance of A to a variable
of type B, as A does not necessarily support the extra behaviour declared in
B; even if you have no extra behaviour, the rule still applies because of
the potential to have extra behaviour.
However, provided B inherits from A, you can assign an instance of B to a
variable of type A.
class C
{
A a;
B b = new B();
a = b; // this will work
// or you can even do this :
a = new B();
}
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer