简体   繁体   中英

Cast derived class type dynamically to base class type C#

public DerivedClass : BaseClass
{
   // code
}

DerivedClass B = (DerivedClass)MethodReturnsBaseClassObject();
B.DoWork();  

There are many Derived classes being inherited from BaseClass . So everytime i need to write a new method to use some of the properties.

Is this possible that using reflection we make DerivedClass type dynamic and do something like this and make it generic.

System.Type type = GetRequestFromSession().GetType();
type B = (type )MethodReturnsBaseClassObject();
Console.WriteLine( B.Name);  
Console.WriteLine( B.Age);  

any help is appreciated.

You can have safe access to members of the derived type (without casts) while enforcing the base class constraint if you employ a generic method with the following signature:

public TDerived MethodReturnsDerivedObject<TDerived>()
    where TDerived : BaseClass

Your calls will then look like this:

DerivedClass b = MethodReturnsDerivedObject<DerviedClass>();

b.ExecuteSomeMethodDefinedInBaseClass();

Console.WriteLine(b.SomePropertyDefinedInDerivedClass);  

This feels like bad design to me: you make something generic that you use as something that isn't. Maybe you should rethink your design.

For what your question is concerned, maybe you can create a proxy method or class that returns the type you expect. This is only useful when there is a low number of methods you call.

Another option is to use the dynamic keyword, but I would advice only to use that if nothing else works.

I would go with Kirill Shlenskiy's answer for now. But I'd also like to suggest moving this method onto the base class itself if it makes sense to do so . There may be tangled dependencies or other weirdness that prohibits this solution, but it may also allow you to have one consumer without using generics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM