Compilerfehler CS0553
-
How it is possible to convert from a base-class: public class Test : Object { .... } .... Object obj = new Object(); Test test = (Test)obj;:confused:
You can't do this.
Object
is the base class andTest
the subclass. TheObject
type knows nothing about theTest
type, so you can't create a new instance ofObject
and cast toTest
. Creating a new instance ofTest
and casting toObject
is OK becauseTest
derives fromObject
and therefore inherits its attributes and behaviour.Paul Marfleet "No, his mind is not for rent To any God or government" Tom Sawyer - Rush
-
You can't do this.
Object
is the base class andTest
the subclass. TheObject
type knows nothing about theTest
type, so you can't create a new instance ofObject
and cast toTest
. Creating a new instance ofTest
and casting toObject
is OK becauseTest
derives fromObject
and therefore inherits its attributes and behaviour.Paul Marfleet "No, his mind is not for rent To any God or government" Tom Sawyer - Rush
Object obj = new Object(); Test test = new Test(); test = (Test)obj; Now I have an InvalidCastException System.InvalidCastException wurde nicht behandelt. Message="Das Objekt des Typs System.Object kann nicht in Typ MyApplication.Test umgewandelt werden." Source="MyApplication"
-
Object obj = new Object(); Test test = new Test(); test = (Test)obj; Now I have an InvalidCastException System.InvalidCastException wurde nicht behandelt. Message="Das Objekt des Typs System.Object kann nicht in Typ MyApplication.Test umgewandelt werden." Source="MyApplication"
daniel99 wrote:
Object obj = new Object(); Test test = new Test(); test = (Test)obj; Now I have an InvalidCastException
How is this different to the code in your first post? It still won't work, for the reasons I outlined earlier. I suggest you get a book on OOP and start reading.
Paul Marfleet "No, his mind is not for rent To any God or government" Tom Sawyer - Rush