Vb.Net Generics mixed with Overloaded Event
I am looking for a little expert design insight. I am trying to save an overloaded property from a generic class.
Base Class
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
Implemented BaseEvent Class
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
开发者_JS百科 End Set
End Property
End Class
Generic 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
Thanks in advance! Ryan
I think your problem is that the property you are trying to overload has the same signature (it only differs by the return type). In general you can't do that. Check out this similar post:
Is there a way to overload a property in .NET?
You have two problems that jump out. The first is that you are trying to give two meanings to a property with the same name. Even if overloading like you did is allowed, it is Very Bad Design(tm). This will be very confusing for anyone that has to look at the code later on.
So pretending that you change the string version to LocationName
in both the derived class and the else branch of the method you showed, we hit the second problem. Roughly speaking, you have a reference to a base class in this method. However, you are trying to call a method from a derived class. To do this, you will either need to restrict the generic type further or perform a type cast.
I'm not sure where fooString
and otherPlace
come from in your example, but if they are both supposed to be the same string, it may be better to have your method take a Func(Of String, BaseEvent)
instead of relying on IsWorkCalendar
. As a side effect, this would remove the need for the method to be generic.
精彩评论