Unable to Cast from Parent Class to Child Class Ask Question

Unable to Cast from Parent Class to Child Class Ask Question

I am trying to cast from a parent class to a child class but I get an InvalidCastException. The child class only has one property of type int. Does anyone know what I need to do?

ベストアンサー1

A simple way to downcast in C# is to serialize the parent and then deserialize it into the child.

 var serializedParent = JsonConvert.SerializeObject(parentInstance); 
 Child c  = JsonConvert.DeserializeObject<Child>(serializedParent);

I have a simple console app that casts animal into dog, using the above two lines of code over here

おすすめ記事