如何在不重新输入所有方法的情况下实现IDataReader?

时间:2012-11-08 19:39:49

标签: asp.net vb.net class implements

我有一个实现IDataReader的类,并且编写了所需的函数,但是我收到一条错误消息,说明

  

类'CSVDataReader'必须为接口'System.Data.IDataRecord'实现'Function GetBoolean(i As Integer)As Boolean'。

IDataReader具有许多功能和属性。如何在不重写所有功能的情况下实现这些功能?

这是我的班级

    Public Class CSVDataReader
    Implements IDataReader
    Private stream As StreamReader
    Private columnsByName As New Dictionary(Of String, Integer)()
    Private columnsByOrdinal As New Dictionary(Of Integer, String)()
    Private currentRow As String()
    Private _isClosed As Boolean = True

    Public Sub New(fileName As String)
        If Not File.Exists(fileName) Then
            Throw New Exception("File [" & fileName & "] does not exist.")
        End If

        Me.stream = New StreamReader(fileName)

        Dim headers As String() = stream.ReadLine().Split(",")
        For i As Integer = 0 To headers.Length - 1
            columnsByName.Add(headers(i), i)
            columnsByOrdinal.Add(i, headers(i))
        Next

        _isClosed = False
    End Sub

    Public Sub Close()
        If stream IsNot Nothing Then
            stream.Close()
        End If
        _isClosed = True
    End Sub

    Public ReadOnly Property FieldCount() As Integer
        Get
            Return columnsByName.Count
        End Get
    End Property

    ''' <summary>
    ''' This is the main function that does the work - it reads in the next line of data and parses the values into ordinals.
    ''' </summary>
    ''' <returns>A value indicating whether the EOF was reached or not.</returns>
    Public Function Read() As Boolean
        If stream Is Nothing Then
            Return False
        End If
        If stream.EndOfStream Then
            Return False
        End If

        currentRow = stream.ReadLine().Split(",")
        Return True
    End Function

    Public Function GetValue(i As Integer) As Object
        Return currentRow(i)
    End Function

    Public Function GetName(i As Integer) As String
        Return columnsByOrdinal(i)
    End Function

    Public Function GetOrdinal(name As String) As Integer
        Return columnsByName(name)
    End Function

    Public Function GetOrdinal(name As String) As Integer
        Return columnsByName(name)
    End Function
End Class

1 个答案:

答案 0 :(得分:1)

您必须实现所有方法和属性。

接口是契约 - 如果对象说它可以提供接口上列出的服务,它必须提供所有这些服务。接口不是基类 - 如果你没有实现某些东西,就没有“模板”代码可以依赖。

没有任何代码可以放在你不感兴趣的方法/属性中(我通常把Throw New NotImplementedException放在一边,所以我知道当我无意中调用了一个我不打算的方法时)。但存根必须在那里。