我有以下的实施产生一个编译器错误通用工厂方法创建泛型类型来龙去脉
“无法隐式转换类型‘
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
- 无济于事。我曾在Stack Exchange的CodeReview上发布过50/50,但认为这同样是一个编码问题和代码设计问题。今天我花了很大一部分时间试图让这个工作,但有很多中断。
我想你需要的只是'公共接口IMenuItemFilter'。但是,如果你检查实际的类型,这是非常不通用的,不是吗?我怀疑你的方案需要泛型,或者至少不适合你的工厂。 –
HimBromBeere
因为IMenuItemFilter指定了与in和out参数相同的TMenuItemType,所以我不能这样做吗?在这个编译器barfs! – Andez
是否有你没有从你的工厂方法返回'IMenuItemFilter'的原因? –