lundi 11 avril 2016

TypeCast using type / string name of class

I have one variable objDataModel of type UDataModel Which is inheriting from AbstractDataModel

public class AbstractDataModel
{
    internal string SomeName { get; set; }
}
public class UDataModel: AbstractDataModel
{

}

public class FDataModel: AbstractDataModel
{

}


public class UCommandProcessor : AbstractCommandProcessor<UserDataModel>
{

}
public class FCommandProcessor : AbstractCommandProcessor<UserDataModel>
{

}
 public abstract class AbstractCommandProcessor<TDataModel> :SomeInterface<TDataModel>
  where TDataModel: AbstractDataModel
 {

 }

I have variable of type of UDataModelType i.e.var tDataModelType= typeOf(UDataModel) using which I am able to create its object.

 var tDataModel = (AbstractDataModel)Activator.CreateInstance(tDataModelType);

I have variable of type UCommandProcessor i.e var processorType= typeOf(UCommandProcessor) I am able to create object of

 var processor = Activator.CreateInstance(processorType);

but I am not able to TypeCast it into UCommandProcessor When I tried

var processor = (AbstractCommandProcessor<AbstractDataModel>)Activator.CreateInstance(processorType);

I am getting exception of

Unable to cast object of type 'ABC.Domain.UCommandProcessor' to type 'ABC.Common.Contract.AbstractCommandProcessor`1[ABC.Common.Contract.AbstractDataModel]'.

Is there any method like

 var processor = (AbstractCommandProcessor<typeOf(tDataModel )>)Activator.CreateInstance(processorType);

Even I Cant do like

 var processor = (AbstractCommandProcessor<typeOf(tDataModel )>)Activator.CreateInstance(processorType);





Aucun commentaire:

Enregistrer un commentaire