zoukankan      html  css  js  c++  java
  • 在VB9中解决多行的Function问题(Visual Studio 2008)

    我们知道,在C#中匿名方法支持多行(有、无)返回值处理程序,不过在VisualBasic中似乎并不这样支持多行的函数或者是过程。怎么办呢?我们来看一个例子(拿List(Of T)做例子)。

    我们知道List(Of T)其中带有Find和FindAll函数——该两个函数需要一个函数Predicate(Of T) As Boolean作为例子,那么我们直接可以尝试这样做(示例性代码):

    Public Function MyFunc(t As T) As Boolean
    ………………
    End Function
    
    List(Of T).Find/FindAll(MyFunc)
    ………………
    

    其实我们可以封一下:

    Public MustInherit Class BasePredicate(Of T As IComparable)
        Public Shared Widening Operator CType(ByVal subclass As BasePredicate(Of T)) As Predicate(Of T)
            Return New Predicate(Of T)(AddressOf subclass.GeneralDo)
        End Operator
    
        Public MustOverride Function GeneralDo(ByVal t As T) As Boolean
    End Class
    

    该类使用了CType的Widening方法(自动把类转化成一个Predicate,而Predicate的需要参数恰巧是子类必须实现的抽象类GeneralDo,比如子类这样实现:

    Public Class IntFindAll
        Inherits BasePredicate(Of Integer)
    
        Public Overrides Function GeneralDo(t As Integer) As Boolean
            Return t Mod 2 = 0
        End Function
    End Class
    

    那么子类可以这样调用:

    Public Class Program
        Shared Sub Main(args As String())
            Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
            For Each i As Integer In numbers.FindAll(New IntFindAll())
                Console.WriteLine(i)
            Next
        End Sub
    End Class
    

    我想,这个可以弥补一些因为在VS2008中VB缺失了C#应有的功能而导致VB某些程序员“心里不平衡”吧,啊哈哈……。

  • 相关阅读:
    [JZOJ3339]【NOI2013模拟】wyl8899和法法塔的游戏
    [JZOJ3337] 【NOI2013模拟】wyl8899的TLE
    UVA 1262 Password
    UVA 10820 Send a Table
    UVA 12716 GCD XOR
    UVA 10791
    UVA 10375 choose and divide (唯一分解定理)
    欧拉函数
    51 Nod 1069 Nim游戏
    51 Nod 1242 矩阵快速幂求斐波那契数列
  • 原文地址:https://www.cnblogs.com/ServiceboyNew/p/2498002.html
Copyright © 2011-2022 走看看