【问题标题】:AddressOf in base class基类中的 AddressOf
【发布时间】:2011-03-16 14:59:13
【问题描述】:

当引用一个方法的地址时,我们应该考虑覆盖还是不考虑?

Class B 
  Inherits A

  Overrides Sub Foo
     Console.WriteLine("B")
  End Sub
End Class


Class A
  Public Sub PFoo
  ... AddressOf Foo ... ' WHAT WILL DO THIS METHOD??? '
  End

  Protected Overridable Sub Foo()
     Console.WriteLine("A")
  End Sub
End Class

【问题讨论】:

  • 你可以测试一下,你知道的。 ;-)

标签: .net vb.net oop


【解决方案1】:

它将打印 B。为了更清楚地表明您的意图,您可以输入 AddressOf Me.Foo。另外,仅供参考,如果您输入 MyClass.Foo,它将打印 A

    Module Module1

    Sub Main()

        Dim b As B = New B
        b.PFoo() ' prints B
        Console.ReadLine()

    End Sub

End Module

Public Class B
    Inherits A

    Protected Overrides Sub Foo()
        Console.WriteLine("B")
    End Sub
End Class

Public Class A
    Public Sub PFoo()
        Dim f As Action = New Action(AddressOf Me.Foo)
        f.Invoke()
    End Sub

    Protected Overridable Sub Foo()
        Console.WriteLine("A")
    End Sub
End Class

【讨论】:

  • 如果你不放我怎么办。但是MyClass.Foo...?
  • 如果您使用 MyClass.Foo 而不是 Me.Foo,则您提供了 Class A 中的方法的地址。在类层次结构中,MyClass 指的是使用它的类。例如,在 A 类中使用 MyClass.Foo 将引用 A 类中的 Foo 方法。但是,在类层次结构中使用 Me.Foo 将查看覆盖 Foo 方法的派生类。如果找不到,它将调用 A 类中的 Foo 方法。因此在本例中,由于 B 类覆盖了 Foo,因此它将在 A 类调用 Me.Foo 时调用。
【解决方案2】:

如果在继承 B 类的/对象实例中调用 PFoo,我相信 PFoo 将引用在继承类中被覆盖的 Foo。

【讨论】:

  • 也就是说,调用bInstance.PFoo()时会输出B?
猜你喜欢
  • 2011-10-30
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 2014-01-30
  • 2017-12-19
相关资源
最近更新 更多