Permanent casting in the superclass

If a:

class Car : Automobile {} 

I can do:

 Car toyota = new Car(); Automobile tauto = (Automobile)toyota; 

but if I do tauto.GetType().Name , it will still be Auto .

Is it possible to cast so that the type is constantly changed to Automobile (without cloning an object)?

The problem I'm trying to overcome is that there is no multiple inheritance in C #, and I need to combine objects (with the same signature) from two services in one way and return the same type.

+5
inheritance c # clone oop
source share
5 answers

Not. This cannot be done without creating a new Automobile object.

However, there is also no reason for this. In principle, the Liskov signature states that any Car should always be handled exactly the same as Automobile , and the user should not have any changes to the expected behavior.

As long as you create the class hierarchy correctly, using Car as Automobile should always be acceptable.


On the side of the note: This is part of why using Type.GetType() not the preferred way of type checking. It is much safer and better to use as keywords in C #. They will return true if you check that tauto is Car .

+11
source share

According to MSDN , you simply throw a link to an object, not to the main object.

0
source share

Your question and what you are trying to do seems to be two different things. No, you cannot change the base type of an object. But what you seem to want to do is create a car type with a set of properties and not actually use a subclass. Instead, you can use Automobile factory.

 public static class AutomobileFactory() { public static Automobile CreateAutomobile(AutomobileType type) { ... } } 

Where AutomobileType is an enumeration. For more information, see google figure C # factory.

0
source share

I'm not sure what exactly you are trying to do, but maybe you could consider a different approach? Instead of trying to combine the functionality of two different classes using inheritance, maybe you could use composition?

http://tiedyedfreaks.org/eric/CompositionVsInheritance.html

 public class Service { public virtual void DoSomething() { } } public class ServiceA : Service { public override void DoSomething() { } } public class ServiceB : Service { public override void DoSomething() { } } public class ServiceA_B : Service { ServiceA serviceA = new ServiceA(); ServiceB serviceB = new ServiceB(); public override void DoSomething() { serviceA.DoSomething(); serviceB.DoSomething(); } } 
0
source share

In some cases, generics can help. If the method contains a generic parameter, the generic type will be evaluated as the declared type of the passed link, not the type of the passed object. For example:

  void foo (t bar)

If foo () is called with (Control) someButton, the type of "bar" will be Button, but the type of T will be Control.

0
source share

All Articles