我确实搜索了所有协方差问题,但没有什么看起来像我的问题。
我有一个用户控件(由于显而易见的原因,此类不能是通用的),它看起来像这样:
class MyUserControl : UserControl
{
private BaseDao<object> _dao;
private AppointmentMapping<object> _mapping;
// I need these 2 generics to type safe the mapping/dao relation
public void RegisterPersistence<T>(BaseDao<T> dao, AppointmentMapping<T> mapping)
{
// These two dont work. even with safe and unsafe casting.
_dao = dao;
_mapping = mapping;
}
}
我已经尝试存储协方差、接口(interface)等的委托(delegate)。它只是不存储对象! 我怎样才能做到这一点?使用 Java 可以轻松实现这一点。
最佳答案
尝试以下操作。 这个想法是在使用时捕获 T 并将其存储在“知道稍后要做什么”的类中。然后通过接口(interface)引用类中的项目(省略类型信息)。 稍后通过接口(interface)调用存储的值。这样您就不需要重构泛型类来实现某些接口(interface)。
class MyUserControl : UserControl
{
// hold a reference to the helper - no generics needed here -> "covariant"
private IHelper helper;
// I need this 2 generics to type safe the relation between the mapping and the dao
public void RegisterPersistence<T>(BaseDao<T> dao, AppointmentMapping<T> mapping) {
// "pass <T>" for later usage
this.helper = new HelperImpl<T>(dao, mapping);
}
// use the stored values...
public void doStuff() {
helper.doStuff();
}
// the non generic interface
private interface IHelper
{
void doStuff();
}
// a generic implementation for storing the items *and* using them.
private sealed class HelperImpl<T> : IHelper
{
private readonly BaseDao<T> dao;
private readonly AppointmentMapping<T> mapping;
public HelperImpl(BaseDao<T> dao, AppointmentMapping<T> mapping) {
this.dao = dao;
this.mapping = mapping;
}
public void doStuff() {
this.dao.foo();
this.mapping.foo();
}
}
}
关于非泛型类中的 C# 协方差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14728892/