Vb.Net Generics与重载事件混合在一起

时间:2011-05-24 20:59:06

标签: vb.net generics polymorphism overloading

我正在寻找一点专家设计见解。我正在尝试从泛型类中保存重载属性。

基类

 Public MustInherit Class BaseEvent

    Public MustOverride ReadOnly Property IsWorkCalendar() As Boolean

    Private _Location As Enums.LocationType
    Public Overridable Property Location() As Enums.LocationType
        Get
            Return _Location
        End Get
        Set(ByVal value As Enums.LocationType)
            _Location = value
        End Set
    End Property

End Class

实施BaseEvent类

Public Class MyEvent
    Inherits BaseEvent

    Private _Location As String
    Public Overloads Property Location As String
        Get
            Return _Location
        End Get
        Set(value As String)
            _Location = value
        End Set
    End Property
End Class

通用类

Public Function GetItemHeaders(Of T As {Core.Events.BaseEvent, New})() As IEnumerable(Of Core.Events.BaseEvent) Implements IMethods.GetItemHeaders
    Dim myEvents = Helper.GetAllEvents(_Service)
    Dim genericEvents As New List(Of BaseEvent)()

        ...loop through items...            

        Dim genericEvent As T = New T()

        If genericEvent.IsWorkCalendar Then
            Dim location As Enums.LocationType = Enums.LocationType.NotConfigured
            If ([Enum].IsDefined(GetType(Enums.LocationType), fooString)) Then
                location = [Enum].Parse(GetType(Enums.LocationType), fooString)
            End If
            genericEvent.Location = location
        Else
            - Always uses the BaseEvent Location and casses an error since I am trying to store a string

            genericEvent.Location = otherPlace
        End If

        ....

        genericEvents.Add(genericEvent)

    Next

    Return genericEvents
End Function

提前致谢! 莱恩

2 个答案:

答案 0 :(得分:0)

我认为您的问题是您尝试重载的属性具有相同的签名(它仅因返回类型而异)。一般来说,你不能这样做。看看这个类似的帖子:

Is there a way to overload a property in .NET?

答案 1 :(得分:0)

你有两个跳出来的问题。首先,您要尝试为具有相同名称的属性赋予两个含义。即使允许像你那样超载,也是非常糟糕的设计(tm)。对于那些必须稍后查看代码的人来说,这将非常混乱。

假设您在所显示的方法的派生类和else分支中将字符串版本更改为LocationName,我们遇到了第二个问题。粗略地说,您在此方法中引用了基类。但是,您尝试从派生类调用方法。为此,您需要进一步限制泛型类型或执行类型转换。

我不确定fooStringotherPlace在您的示例中来自何处,但如果它们都应该是相同的字符串,那么让您的方法采用{{}可能会更好1}}而不是依赖Func(Of String, BaseEvent)。作为副作用,这将消除该方法的通用性。