lundi 11 avril 2016

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.





Aucun commentaire:

Enregistrer un commentaire