首页 > 解决方案 > 有没有办法返回作为子类的类型?

问题描述

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

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 查找特定的产品类型。

标签: c#generics

解决方案


实现一个基本接口,您可以在其中定义您的产品具有一个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 字段,该字段应该存在于任何FruitProductCerealProduct您发送到的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);
    }
}

推荐阅读