C#实现接口的通用方法

时间:2018-08-23 15:36:05

标签: c#

请帮助我使此代码正常工作。

现在它在行x => x.Model上失败,并显示错误消息:

  

无法将lambda表达式转换为预期的委托类型

我没有想法。 谢谢。

interface IFetchStrategy<TEntity> where TEntity : class
{
    Expression<Func<TEntity, TProperty>> Apply<TProperty>();
}
class ModelFetchStrategy : IFetchStrategy<UserCar>
{
    public Expression<Func<UserCar, Model>> Apply<Model>()
    {
        return x => x.Model;
    }
}
class Model { }
class UserCar
{
     public Model Model { get; set; }
}

我需要通过类似的代码使用此策略:

IEnumerable<UserCar> Get(IEnumerable<IFetchStrategy<UserCar>> strategies)   

1 个答案:

答案 0 :(得分:1)

这里的问题是“模型”不是您认为的那样。它不是“ Model”类的实例,而是具有名称的模板属性(基本上是“ TProperty”,名称不同)。相反,“应用”必须不带任何模板参数。

interface IFetchStrategy<TEntity, TProperty> where TEntity : class
{
    Expression<Func<TEntity, TProperty>> Apply();
}
class ModelFetchStrategy : IFetchStrategy<UserCar, Model>
{
    public Expression<Func<UserCar, Model>> Apply()
    {
        return x => x.Model;
    }
}
class Model { }
class UserCar
{
    public Model Model { get; set; }
}
相关问题