Vb.Net泛型与重载事件混合

问题描述

| 我正在寻找一些专业的设计见解。我试图从泛型类保存重载的属性。 基类
 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
提前致谢! 瑞安     

解决方法

我认为您的问题是,您尝试重载的属性具有相同的签名(仅返回类型不同)。通常,您不能这样做。看看这个类似的帖子: 有没有一种方法可以重载.NET中的属性?     ,您遇到两个问题。第一个是您要为具有相同名称的属性赋予两种含义。即使允许像您一样重载,它也是Very Bad Design(tm)。对于以后不得不看代码的任何人来说,这将非常令人困惑。 因此,假设您在派生类和显示的方法的else分支中都将字符串版本更改为
LocationName
,我们遇到了第二个问题。粗略地说,您可以在此方法中引用基类。但是,您正在尝试从派生类调用方法。为此,您将需要进一步限制泛型类型或执行类型转换。 我不确定示例中的
fooString
otherPlace
来自何处,但是如果假定它们都是相同的字符串,则最好让方法采用
Func(Of String,BaseEvent)
而不是依赖rely7ѭ。作为副作用,这将消除对通用方法的需要。