Tuesday, 15 May 2012

C# Casting a Class implementing interface to Class based on type -


My question is best explained with an example:

  public IPlotModel MyPlotModel; public ??? CastedModel; Public Constructor () {MyPlotModel = New PlotModel (); // It should be intimate with other types I / E: MyPlotModel = new OtherModel (); CastedModel = (MyPlotModel.GetType ()) MyPlotModel; }  

This is basically what I want. CastedModel should be inserted on the basis of MyPlotModel.

I have had some success in using Convert. ChangeType () I manage to change the type of CastedModel to the right type, but I can not manage to convert the value of Castedodal to MyPlotModel.

This is what I have done:

  convert.Change type (Castemodel, Myoplot.Model.Gettype ()); CastedModel = MyPlotModel;  

But MyPlotModel is still recognized as an interface even though it has been started as a PlotModel.

Thanks in advance, Alexander.

It looks like you should use the normal range:

  Public class examples & lt; TPlotModel & gt; Where TPlotModel: IPlotModel, new () {public TPlotModel PlotModel {get; Private set; } Public Example () {this.PlotModel = New TPlotModel (); }}  

that you can instantiate and use

  var myExample = new example & lt; MyPlotModel & gt; (); MyPlotModel foo = myExample.PlotModel;  

No comments:

Post a Comment