c# - 有没有办法返回作为子类的类型?
问题描述
我想要一个基本上可以做到这一点的函数:
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 字段,该字段应该存在于任何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);
}
}
推荐阅读
- mysql - 选择 后的十进制数。大于 0
- scala - 连接后是否有只选择一个数据框列的简写?
- c# - 单元测试:尽管 Returns() 设置为 true,但模拟服务返回默认布尔值 (false)。C# xunit 最小起订量
- powershell - 当用户使用 ADSI 脚本时防止权限提升
- github-actions - 如何在 PR 评论编辑上运行 GitHub Action?
- html - ngClass 有没有更好的方法让样式始终存在并根据条件添加其他样式
- javascript - Wix - 如何远程登录外部站点
- javascript - 按下退出键时需要关闭模态弹窗
- delphi - When to choose which type of Delphi unit?
- javascript - React Hooks 中的类型错误