首页 > 解决方案 > 通用方法不调用接口的实现成员

问题描述

尝试通过使用泛型方法向 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");

标签: c#.netlinqgenericsinterface

解决方案


让我们后退一步,如果你要手写这个,没有你的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"));

推荐阅读