【问题标题】:Vb.Net Generics mixed with Overloaded EventVb.Net 泛型与重载事件混合
【发布时间】:2011-05-24 20:59:05
【问题描述】:

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

基类

 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

提前致谢! 瑞恩

【问题讨论】:

  • 很高兴看到人们使用带有 OOP 视角的 VB,而不是人们仍然坚持的 VB6 方式。向你致敬!
  • 谢谢,我是一名 VB.Net/C# 程序员。这个新工作全是vb,所以我的大脑又该切换模式了。

标签: vb.net generics polymorphism overloading


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你有两个问题跳出来。首先是您试图为同名的属性赋予两种含义。即使允许像您那样重载,它也是非常糟糕的设计(tm)。对于以后必须查看代码的任何人来说,这将非常混乱。

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

    我不确定fooStringotherPlace 在您的示例中来自哪里,但如果它们都应该是同一个字符串,那么最好让您的方法采用Func(Of String, BaseEvent) 而不是依赖在IsWorkCalendar。作为副作用,这将消除对泛型方法的需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-11
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2015-07-11
      • 2010-11-22
      相关资源
      最近更新 更多