非泛型类中的 C# 协方差

标签 c# covariance

我确实搜索了所有协方差问题,但没有什么看起来像我的问题。

我有一个用户控件(由于显而易见的原因,此类不能是通用的),它看起来像这样:

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/

相关文章:

C++ 模板协变

c#-4.0 - 接口(interface)协方差问题

c# - 在 C# 中,为什么 List<string> 对象不能存储在 List<object> 变量中

java 从 List<B> 转换为 List<A>,其中 B 扩展了 A

c# - 使用表达式主体成员中重新分配的参数进行递归调用

c# - BlockingCollection 或 Queue<T> 用于作业?

c# - 如何在 WinRT 中的按钮中将文本放置在图像上

javascript - 如何从位于 updatePanel 的 Gridview 中的 LinkBut​​ton 触发 Onclick 事件?

c# - 为什么我应该使用异步操作而不是同步操作?

c# - C# 中的协变和逆变