1

Suppose I have the following parent class defined:

Public Class Parent

    Public Property Prop1 As String = "MyDB1"

End Class

And I wish to inherit it, but want that property to have a different value for the child class.

I figured I could do it as follows:

Public Class Child
    Inherits Parent

    Public Sub New()
        MyBase.New()
        MyBase.Prop1 = "MyDB2"
    End Sub

End Class

But I was wondering if this was the best way to do this or if there is something like an Overridable property OR if this is just bad programming practice as a whole?

Thanks!

4

2 回答 2

3

在 c# 中,为了让一个属性可以被覆盖,你可以将类成员标记为virtual,并且这个关键字的 vb.net 等价是Overridable.

public virtual int MyProperty {get;set;}

这个属性可以在子类中被覆盖,如下所示:

 public override int MyProperty {
  get{ 
         //return some other thing
     }
  } 

Vb.NET 等价物:

在超级班:

 Public Overridable Property MyProperty As Integer
        Get

        End Get

        Set

        End Set

    End Property

在子类中:

  Public Overrides Property MyProperty As Integer
        Get
                //return some other thing
        End Get

    End Property
于 2012-12-13T19:31:03.413 回答
2

根据您的评论,这是我的看法:

  • 如果您可以控制基类,则Overridable如果意图是根据派生类型的业务规则更改其值,请执行此操作
  • 如果您无法控制基类,并且需要“覆盖”该属性,则可以“隐藏”基类属性;在 C# 中,它看起来像new public int MyProperty { ... },但我不确定这是如何在 VB 中完成的
  • 如果您只需要该属性返回不同的值,那么您所做的似乎很好
于 2012-12-13T19:38:22.943 回答