[英]Generic Factory method to create generic types ins and outs
我有以下实现生成编译器错误
“无法将类型'
ParentMenuItemFilter
'隐式转换为'IMenuItemFilter<MenuItem>
'。存在显式转换(您是否错过了转换?)
public class MenuItem
{
// implementation removed for clarity
}
public class ParentMenuItem : MenuItem
{
// implementation removed for clarity
}
public interface IMenuItemFilter<TMenuItemType>
where TMenuItemType : MenuItem
{
TMenuItemType ApplySecurity(TMenuItemType menuItem);
}
public class ParentMenuItemFilter : IMenuItemFilter<ParentMenuItem>
{
public ParentMenuItem ApplySecurity(ParentMenuItem menuItem)
{
// implementation removed for clarity
}
}
public class MenuItemFilterFactory
{
public IMenuItemFilter<MenuItem> Create<TMenuItemType>(TMenuItemType menuItem)
where TMenuItemType : MenuItem
{
if (typeof(TMenuItemType) == typeof(ParentMenuItem))
{
// here is the errored line!...
return new ParentMenuItemFilter(this);
}
else if (/* create some other types*/)
{
...
}
}
}
所以我的两个最好的朋友,协方差和逆变进来发挥。 我想实现上述如果可能的话,通过通用的工厂方法,该方法将返回的相应实例IMenuItemFilter
,这是会后的行动menuItem
参数的Create
方法。
我想将MenuItem
实例传递给工厂方法,以便解决此问题。
我已尝试in TMenuItemTypeIn, out TMenuItemTypeOut
中输入和输出in TMenuItemTypeIn, out TMenuItemTypeOut
在接口和其他定义中in TMenuItemTypeIn, out TMenuItemTypeOut
- 无济于事。 我在Stack Exchange上将其发布到CodeReview时是50/50,但认为这同样是编码问题以及代码设计问题。 我今天花了大部分时间试图让这个工作,但有很多中断。
如果这不是一个过于简单的例子,那么每个类型应该有一个方法,例如CreateParentMenuItemFilter
或类似的东西。 你的通用方法似乎只会使事情变得复杂而没有任何好处。
我想你需要的只是public interface IMenuItemFilter<out TMenuItemType>
。 但是,使用基于泛型类型参数执行不同操作的泛型方法有点奇怪而不是泛型的意图 - 这就是为什么它们被称为泛型 :它们对不同的类做同样的事情。
所以我建议你的工厂不通用:
public class MenuItemFilterFactory
{
public IMenuItemFilter Create(MenuItem menuItem)
{
if (menuItem.GetType() == typeof(ParentMenuItem))
{
return new ParentMenuItemFilter(this);
}
else if (/* create some other types*/)
{
...
}
}
}
但是,假设您的接口具有非泛型版本,通用版本也是如此:
public interface IMenuItemFilter
{
}
public interface IMenuItemFilter<TMenuItemType> : IMenuItemFilter
where TMenuItemType : MenuItem
{
TMenuItemType ApplySecurity(TMenuItemType menuItem);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.