我想要一个基本上做到这一点的函数:
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 查找特定的产品类型。
实现一个基本接口,您可以在其中定义您的产品具有一个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 字段,该字段应该出现在 anyFruitProduct
或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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句