VB.NET Interfaces

前端 未结 2 1513
清歌不尽
清歌不尽 2021-02-06 12:29

I am not quite clear as to why or when to use Interfaces. Can someone post a complete, simple and small example of an Interface using VB.NET in a Console Application. How is it

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 12:57

    Consider this simple interface:

    Public Interface IWeightedValue
        Public ReadOnly Property Weight As Double
        Public ReadOnly Property Value As Double
    End Interface
    

    Without even writing any more code, I can start dealing with this concept in other parts of my code. For instance:

    Public Function GetWeightedAverage(ByVal points As IEnumerable(Of IWeightedValue)) As Double
        Dim totalWeight As Double = 0.0
        Dim totalWeightedValue As Double = 0.0
    
        For Each point As IWeightedValue in points
            totalWeight += point.Weight
            totalWeightedValue += (point.Weight * point.Value)
        Next
    
        Return totalWeightedValue / totalWeight
    End Function
    

    And voila -- now for any class I write, if I just make it implement IWeightedValue then I can calculate the weighted average for a collection of instances of this class.

提交回复
热议问题