vendredi 1 juillet 2016

Static method return base class instance

I have the following classes:

//some base class
public abstract class MyObject<T>{

      public static T FromObject(object anotherObject){
       var t = Activator.CreateInstance<T>();
       //  some reflection logic here
       return t;
  }     
}

public class Product: MyObject<Product>{
}

public class ProductCart: MyObject<ProductCart>{
  public ICollection<Product> Products{get;set;}
}

public class Basket: ProductCart{
  public int BasketId{get;set;}
}

public class Order: ProductCart{
  public int OrderId{get;set;}
}

So now I could build my model like this:

var products = serviceContext.Products.Select(Product.FromObject).ToList(); // no problem here

var basket = Basket.FromObject(serviceContext.Basket); // problem is here - instance of ProductCart is returned

var order = Order.FromObject(serviceContext.Order); // same problem, instance of ProductCart

Is there a way somehow to solve it and get converted Basket and Order instead of base ProductCart?

The goal is:

 var basket = Basket.FromObject(serviceContext.Basket); // return instance of Basket inherited from ProductCart

Thanks for helping.





Aucun commentaire:

Enregistrer un commentaire