有没有一种方法可以返回作为子类的Type?

时间:2018-07-25 19:07:23

标签: c# generics

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

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),并且无法访问实体框架。在执行任何查询之前,我需要一种映射到表的类型。我没有为每种产品类型编写相同的代码,而是尝试为Product编写代码,然后根据产品的ID查找特定的产品类型。

1 个答案:

答案 0 :(得分:1)

实现一个基本界面,您在其中定义产品具有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; }
}

最后一次查找将指定其为IProduct的类型(因此,您可以访问ID字段,该字段应显示在您发送给的任何FruitProductCerealProductProductLookup

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);
    }
}
相关问题