C# 将泛型接口的实现分配给属性
我有一个接口C# 将泛型接口的实现分配给属性,c#,.net,generics,C#,.net,Generics,我有一个接口 public interface IStrategy<T> where T : BaseModel { T GetModel(Guid userId); } 现在,在下面的方法中,我可以传递一个新的ConcreteStrategy实例,一切正常 public class Manager { public TModel GetContentModel<TModel>(IStrategy<TModel> strategy, Gu
public interface IStrategy<T> where T : BaseModel
{
T GetModel(Guid userId);
}
现在,在下面的方法中,我可以传递一个新的ConcreteStrategy
实例,一切正常
public class Manager
{
public TModel GetContentModel<TModel>(IStrategy<TModel> strategy, Guid userId)
where TModel : ModelBase
{
return strategy.GetContentModel(userId);
}
}
公共类管理器
{
公共TModel GetContentModel(IStrategy策略,Guid用户ID)
其中TModel:ModelBase
{
返回策略.GetContentModel(userId);
}
}
但是如果我尝试将它分配给这样的属性,我会得到一个错误
public class Strategies
{
public static IStrategy<ModelBase> MyStrategy { get; set; }
}
Strategies.MyStrategy = new ConcreteStrategy();
公共课堂策略
{
公共静态IStrategy MyStrategy{get;set;}
}
Strategies.MyStrategy=新的具体策略();
有没有办法用C#实现这一点?
我希望能够创建一个工厂方法,封装要使用的策略的逻辑,并只返回某种类型的策略类的实例(如ConcreteStrategy
)
我得到的错误是:
无法将类型
IStrategy
隐式转换为IStrategy
您需要制作界面:
公共接口策略,其中T:BaseModel
请注意,只有当T
仅出现在界面的输出位置时,它才会起作用(您显示的代码就是这种情况,但我不知道它是否是您的真实代码)
public class Strategies
{
public static IStrategy<ModelBase> MyStrategy { get; set; }
}
Strategies.MyStrategy = new ConcreteStrategy();
public interface IStrategy<out T> where T : BaseModel