I recently saw some netizens asking questions about strong conversion of objects in C # On the Forum. Although I have been familiar with C #, I was the first to contact this feature, so here we will find some materials to share with you.
I. Code
[Csharp]
Class Program
{
Static void Main (string [] args)
{
A a = new ();
B B = new B ();
B. a = 300;
B. B = 20;
B e = a. Clone () as B; // an error will be executed but it will become B. clone () as B.
System. Console. WriteLine (e. );
}
}
Public class A: ICloneable
{
Public ()
{
}
Public int a = 200;
# Region ICloneable Member
Public virtual object Clone ()
{
Return MemberwiseClone ();
}
# Endregion
}
Public class B:
{
Public int B = 10;
Public B (): base ()
{
}
Public override object Clone ()
{
B c = base. Clone () as B; // Why can the base class be converted to a derived class ?????????
C. B = 100;
Return c;
}
}
Class Program
{
Static void Main (string [] args)
{
A a = new ();
B B = new B ();
B. a = 300;
B. B = 20;
B e = a. Clone () as B; // an error will be executed but it will become B. clone () as B.
System. Console. WriteLine (e. );
}
}
Public class A: ICloneable
{
Public ()
{
}
Public int a = 200;
# Region ICloneable Member
Public virtual object Clone ()
{
Return MemberwiseClone ();
}
# Endregion
}
Public class B:
{
Public int B = 10;
Public B (): base ()
{
}
Public override object Clone ()
{
B c = base. Clone () as B; // Why can the base class be converted to a derived class ?????????
C. B = 100;
Return c;
}
}
Ii. Explanation
1. Explain "B e = a. Clone () as B; // here it will run incorrectly but it will become B. clone () as B and it will be normal"
You instantiate two objects, but the parent class does not have memory related to the object of the subclass and cannot be converted
The analysis of this code is simple:
A. Clone () returns an object of type. A is A base class without class B memory, so the base class cannot be forcibly converted to A derived class.
B. Clone () to obtain B-type objects. So it can be as B.
Here is an example:
[Csharp]
A a = new ();
B B = new B ();
A a2 = B; // This is acceptable.
B b2 = a2 as B; // This forced conversion can also be successful.
A a = new A (); www.2cto.com
B B = new B ();
A a2 = B; // This is acceptable.
B b2 = a2 as B; // This forced conversion can also be successful.
2. Explain "B c = base. Clone () as B; // Why can the base class be changed to a derived class ????????? "
This is because the instantiated object itself is B, and B contains A, so it can be converted.
Variable a points to A Class a Object no matter what type you declare. Variable B points to a Class B object no matter what type you declare. It is not to say that "you can change the base class to A derived class", but to confuse the type with the object itself, but that object B is both A Class Object and B class object, that is
If (B is A & B is B)
Return true;
You can try it. This returns true.