简体   繁体   中英

Assigning implementation of a generic interface to a property

I have an interface

public interface IStrategy<T> where T : BaseModel
{
    T GetModel(Guid userId);
}

and a concrete class inheriting the interface specifying that it should be a ConcreteModel

 public class ConcreteStrategy: IStrategy<ConcreteModel>
 {
     ConcreteModel GetModel(Guid userId) { ... }
 }

Now in the following method I can pass a new instance of ConcreteStrategy and everything works

 public class Manager
 {
    public TModel GetContentModel<TModel>(IStrategy<TModel> strategy, Guid userId)
        where TModel : ModelBase
    {
        return strategy.GetContentModel(userId);
    }
 }

But if I try to assign it to a property like this I get an error

public class Strategies
{
    public static IStrategy<ModelBase> MyStrategy { get; set; }
}

Strategies.MyStrategy = new ConcreteStrategy();

Is there a way I can achieve this in C# ? I want to be able to make a factory method that encapsulates the logic for which strategy to use and just return an instance of some type of strategy class (like ConcreteStrategy ).

The error I am getting is:

Cannot implicitly convert type IStrategy<ModelBase> to IStrategy<ConcreteModel>

You need to make your interface covariant :

public interface IStrategy<out T> where T : BaseModel

Note that it will work only if T only appears in an output position in the interface (which is the case in the code you have shown, but I don't know if it's your real code).

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