[英]Generic method not invoking interface's implementation member
Trying to reduce the code duplication by using generic methods to send a parameterized query to DB.尝试通过使用通用方法向数据库发送参数化查询来减少代码重复。 Went for the following approach, but the query does not seem to resolve the implementation member's value.
寻求以下方法,但查询似乎没有解析实现成员的值。 It works if the return type is strictly defined in
GetQuery
method, but then it's just back to square one.如果在
GetQuery
方法中严格定义了返回类型,它会起作用,但它只是回到第一个。 It also works if the CountryCode
value is hardcoded inside GetQuery
method.如果它也
CountryCode
值内硬编码GetQuery
方法。
Why doesn't the CountryCode
use the value from the FrenchChocolate
instance?为什么不
CountryCode
使用从值FrenchChocolate
实例?
Interface:界面:
public interface IChocolate
{
public string ManufacturerId { get; set; }
public string CountryCode { get; }
}
Implementation:执行:
public class FrenchChocolate : IChocolate
{
public string ManufacturerId { get; set; }
public string CountryCode => "FR";
// ...other properties...
}
Query method (yes, it's ugly, feel free to propose a better way)查询方法(是的,很丑,欢迎提出更好的方法)
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;
}
Method call:方法调用:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(GetQuery<FrenchChocolate>("123"));
This works, but defeats the purpose:这有效,但违背了目的:
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;
}
This as well:这也是:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(c => c.ManufacturerId == manufacturerId && c.CountryCode == "FR");
Lets take a step backwards, if you were to write this out longhand, without your GetQuery
function, you'd write:让我们向后退一步,如果您要直接写出它,而没有
GetQuery
函数,您会这样写:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(c => c.ManufacturerId == "123" && c.CountryCode == "FR");
Now, if you want to offload making that query to a GetQuery
function it would simply be现在,如果您想将该查询卸载到
GetQuery
函数,则只需
private static Expression<Func<T, bool>> GetQuery<T>(string manufacturerId, string countryCode) where T: IChocolate
{
return c => c.ManufacturerId == manufacturerId && c.CountryCode == countryCode;
}
And和
var frenchChoc = await GetChocFromDb<FrenchChocolate>(GetQuery<FrenchChocolate>("123","FR"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.