代码之家  ›  专栏  ›  技术社区  ›  user875234

是否有返回子类类型的方法?

  •  0
  • user875234  · 技术社区  · 7 年前

    我想要一个基本上可以做到这一点的函数:

    public static Type GetProductType(int id)
    {
        var typeString = db.GetTypeString(id);
        return Type.GetType(typeString);
    }
    

    我想这样使用:

    public static Product GetProduct(int id)
    {
        var productType = GetProductType(id);
        return db.Table<productType>()
            .Single(p => p.Id == id);
    }
    

    但问题是 p.id 在里面 .Single(p => p.id == id) . 代码不知道P(即ProductType)具有ID属性。所以我能想到的一个方法就是 Type 被送回的 GetProductType 被约束到 Product (具有ID属性)。

    它的设置是这样的,因为我使用的是SQL NET PCL(用于Xamarin的sqliite),并且没有访问实体框架的权限。在执行任何查询之前,我需要一个映射到表的类型。而不是为每种产品类型编写相同的代码 产品 然后根据产品的ID查找特定的产品类型。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Blue    7 年前

    实现一个基本接口,其中定义产品的 Id 财产:

    public interface IProduct
    {
        int Id { get; set; }
    }
    

    定义实际的类,并确保它们实现 IProduct :

    public class FruitProduct : IProduct
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Variety { get; set; }
    }
    
    public class CerealProduct : IProduct
    {
        public int Id { get; set; }
        public string Brand { get; set; }
        public int SugarContent { get; set; }
    }
    

    最后的查找将指定它是 i-乘积 (这样,您就可以访问ID字段,该字段应该出现在 FruitProduct CerealProduct 你发送到 ProductLookup )

    public class ProductLookup<T> where T : IProduct
    {
        public static T GetProduct(int id)
        {
            // var productType = GetProductType(id);
            //You can pass either FruitProduct or CerealProduct here (Although, you will ONLY
            //be able to access Id here, as this function only knows it's an IProduct)
            return this.db<T>()
                .Single(p => p.Id == id);
        }
    }