开发者

How does down casting quite work? C#

开发者 https://www.devze.com 2023-02-04 01:58 出处:网络
If I instantiate an object like such : Person hello = new Person(); I\'m allowed to do somethin开发者_如何学Pythong like

If I instantiate an object like such :

Person hello = new Person();

I'm allowed to do somethin开发者_如何学Pythong like

Employee test = (Employee)hello;

What does this do? What'd downcasting all about? So when we allocate memory for the base, and down cast what happens there?


It will not work. It will throw InvalidCastException at runtime. (assuming Employee : Person).


You should be familiar with this Casting and Type Conversions

If we assume that class Employee extend Person and there is no implicit implementation then at runtime it will throw InvalidCastException.


Unless you didn't specify implicit or explicit operator conversion from Person to Employee that will throw InvalidCastException.

0

精彩评论

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