我有以下课程:
//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;}
}
所以现在我可以像这样构建我的模型:
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
有没有办法以某种方式解决它并转换篮子和订单而不是基础ProductCart?
目标是:
var basket = Basket.FromObject(serviceContext.Basket); // return instance of Basket inherited from ProductCart
感谢您的帮助。
答案 0 :(得分:1)
如果您可以更改类定义,则可以将类型传递给ProductCart
,如下所示:
public class ProductCart<T> : MyObject<T> { }
public class Basket : ProductCart<Basket> { }
public class Order : ProductCart<Order> {}
在您的定义中,您告诉Basket.FromObject
明确返回ProductCart
s(继承自MyObject<ProductCart>
)。
如果您无法更改继承树,则可以选择隐藏原始方法(或将其放置在工厂中):
public class Basket : ProductCart
{
public int BasketId { get; set; }
public Basket FromObject(object anotherObject)
{
return MyObject<Basket>.FromObject(anotherObject);
}
}
答案 1 :(得分:0)
那是因为Basket
是MyObject<ProductCart>
,而不是MyObject<Basket>
。
如果您不想重新定义层次结构,则应根据传递的对象定义静态方法的返回类型,如下例所示:
using System;
public abstract class MyObject<T> {
public static TOtherObject FromObject<TOtherObject>(TOtherObject anotherObject) where TOtherObject : MyObject<T> {
var newOtherTypeInstance = Activator.CreateInstance<TOtherObject>();
// some reflection logic here
return newOtherTypeInstance;
}
}
public class ProductCart : MyObject<ProductCart> {
}
public class Basket : ProductCart {
public int BasketId { get; set; }
}
public class Order : ProductCart {
public int OrderId { get; set; }
}
class Program {
static void Main(string[] args) {
Order o = new Order();
var basket = Basket.FromObject(o);
}
}
当然,此时评论的实际执行情况&#34;这里有一些反思逻辑&#34;可能会变得更加复杂:)