简体   繁体   中英

C# implement generic method of interface

Please help me to make this code work.

Now it fails on row x => x.Model with error message:

Cannot convert lambda expression to intended delegate type

I don't have ideas. Thank you.

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; }
}

I need to use this strategies with similar code:

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

The issue here is that "Model" is not what you think it is. It is not an instance of the "Model" class, but rather it is a template property with a name (basically it is "TProperty" by a different name). Instead "Apply" has to take in no templates parameter.

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM