c# - 通用方法不调用接口的实现成员
问题描述
尝试通过使用泛型方法向 DB 发送参数化查询来减少代码重复。采用以下方法,但查询似乎无法解析实现成员的值。如果在GetQuery
方法中严格定义了返回类型,它就可以工作,但它只是回到了第一方。如果CountryCode
值在GetQuery
方法内部硬编码,它也可以工作。
为什么不CountryCode
使用FrenchChocolate
实例中的值?
界面:
public interface IChocolate
{
public string ManufacturerId { get; set; }
public string CountryCode { get; }
}
执行:
public class FrenchChocolate : IChocolate
{
public string ManufacturerId { get; set; }
public string CountryCode => "FR";
// ...other properties...
}
查询方法(是的,很丑,随意提出更好的方法)
private static Expression<Func<T, bool>> GetQuery<T>(string manufacturerId) where T: IChocolate
{
T obj = (T)Activator.CreateInstance(typeof(T));
return c => c.ManufacturerId == manufacturerId && c.CountryCode == obj.CountryCode;
}
方法调用:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(GetQuery<FrenchChocolate>("123"));
这有效,但违背了目的:
private static Expression<Func<**FrenchChocolate**, bool>> GetQuery<T>(string manufacturerId) where T: IChocolate
{
T obj = (T)Activator.CreateInstance(typeof(T));
return c => c.ManufacturerId == manufacturerId && c.CountryCode == obj.CountryCode;
}
这也是:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(c => c.ManufacturerId == manufacturerId && c.CountryCode == "FR");
解决方案
让我们后退一步,如果你要手写这个,没有你的GetQuery
函数,你会写:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(c => c.ManufacturerId == "123" && c.CountryCode == "FR");
现在,如果您想将该查询卸载到一个GetQuery
函数,那么它只是
private static Expression<Func<T, bool>> GetQuery<T>(string manufacturerId, string countryCode) where T: IChocolate
{
return c => c.ManufacturerId == manufacturerId && c.CountryCode == countryCode;
}
和
var frenchChoc = await GetChocFromDb<FrenchChocolate>(GetQuery<FrenchChocolate>("123","FR"));
推荐阅读
- javascript - 如何在javascript中的石头剪刀布中添加5轮?
- python - 不推荐使用的警告 - mataplotlib 库中的 where 参数
- ios - 用 JSONdata 填写 UITableViewCell
- intellij-idea - IntelliJ 无法使用 JDK 11 运行 JUnit5 测试
- javascript - 如何在按钮单击操作时重新加载同一页面,即在反应中删除?
- r - 如何使用单独的 R 中的输入创建闪亮的反应函数
- .net-core - 验证收到消息的 SHA256 签名
- java - 哪个方法将从接口或类中获得覆盖?
- sql - emp 更改商店时的前 3 名员工
- javascript - JQuery html 方法中的 HTML 代码不起作用(它显示内容但 javascript 调用不起作用)