【问题标题】:A little vb.net interface explaination一点vb.net界面说明
【发布时间】:2011-04-04 02:01:40
【问题描述】:

谁能解释一下这个接口的 (of Out T) 组件?我对接口的工作方式非常熟悉。我也明白 T 指的是一种类型...... Out 部分发生了什么。

Public Interface IPageOfItems(Of  Out T)
Inherits IEnumerable(Of T)
        Property PageNumber() As Integer
        Property PageSize() As Integer
        Property TotalItemCount() As Integer
        ReadOnly Property TotalPageCount() As Integer
        ReadOnly Property StartPosition() As Integer
        ReadOnly Property EndPosition() As Integer
    End Interface

【问题讨论】:

    标签: asp.net vb.net interface


    【解决方案1】:

    这表明接口在泛型参数 T 中是协变的。检查 this article 中的泛型变量标题,它解释了 VB.NET 2010 (.NET Fx 4.0) 中的新功能。

    简而言之,协方差将允许用较小的类型(例如子类)代替较大的类型。例如,如果 Tiger 是从 Animal 继承的,那么我们可以使用 IEnumerable(Of Tiger) 代替 IEnumerable(Of Animal)。 Eric Lippert 在blog posts 系列中很好地解释了方差(在 C# 上下文中)。

    【讨论】:

      【解决方案2】:

      .NET 4.0 引入了covariance and contravariance of generic types。这是什么意思。

      协方差

      这里的Out关键字表示类型是协变的。协变类型 T(Of D) 可以转换为类型 T(Of B),其中 D 派生自 B。当类型 T(Of D) 仅使用 D 值作为 输出 时,这是可能的(因此单词 输出)。

      例如,IEnumerable(Of Out T) 接口是协变的,因为它的方法都不接受T 类型的任何参数。因此,IEnumerable(Of String) 可以转换为IEnumerable(Of Object)——如果它提供对字符串的可枚举访问,那么它提供对对象的可枚举访问(因为字符串对象)。

      逆变

      相反,In 关键字可以应用于符合逆变条件的类型。逆变类型 T(Of B) 可以转换为类型 T(Of D),其中 D 派生自 B。当类型 T(Of B) 仅使用 B 值作为 输入 时,这是可能的(因此单词 )。换句话说,逆变与协方差正好相反。

      逆变类型的一个很好的例子是IComparer(Of In T) 接口。该接口不提供返回T 值的方法;因此IComparer(Of Object) 可以转换为IComparer(Of String)——毕竟,如果它可以比较对象,它就可以比较字符串。

      【讨论】:

        【解决方案3】:

        这是 .NET 4 的新功能,允许您使用通用参数指定差异。几乎所有你需要知道的:

        http://msdn.microsoft.com/en-us/library/dd799517.aspx

        【讨论】:

          猜你喜欢
          • 2012-10-09
          • 1970-01-01
          • 2020-03-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多