遇到了一些我觉得有趣的东西,并希望得到解释。
编辑
这个问题并不是要回答应该采取什么措施来解决它。我知道修复。我想要解释为什么编译器会这样做。前任。在这种情况下是否不考虑私有功能?
问题
我有一个类,它有一个名为 WhatIs 的公共共享(静态)函数。WhatIs 接受一个包含对象集合的参数。代码遍历这个集合并调用一个 WhatIs 函数,该函数的参数类型与对象是什么相匹配。
执行时,会引发 InvalidCastException 异常,因为执行尝试调用启动此的 WhatIs 函数,而不是所提供类型的函数。
这很奇怪,但让我感到奇怪的是,当您将私有共享功能更改为公共共享时,它工作正常。
更奇怪的是,当您显式转换对象时,即使该函数是私有的,它也可以工作。
什么?!有人请解释
代码
胆量:
Public Class House
Public Property Furniture As ICollection(Of Object)
Public Sub New()
Furniture = New List(Of Object)
End Sub
End Class
Public Class Chair
Public Property IsComfortable As Boolean
End Class
Public Class Table
Public Seats As Integer
End Class
Public Class HouseExaminer
Public Shared Function WhatIs(thing As House) As String
Dim isA As String = "a house that contains "
For Each item In thing.Furniture
isA &= WhatIs(item)
Next
Return isA
End Function
Private Shared Function WhatIs(thing As Chair) As String
Return "a " & If(thing.IsComfortable, "comfortable", "uncomfortable") & " chair "
End Function
Private Shared Function WhatIs(thing As Table) As String
Return "a table that seats " & thing.Seats & " iguanas"
End Function
End Class
去测试
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports stuff
<TestClass()>
Public Class HouseExaminerTests
<TestMethod()>
Public Sub TestWhatIs()
Dim given As New House()
Dim expected As String
Dim actual As String
given.Furniture.Add(New Chair() With {.IsComfortable = True})
given.Furniture.Add(New Table() With {.Seats = 4})
expected = "a house that contains a comfortable chair a table that seats 4 iguanas"
actual = HouseExaminer.WhatIs(given)
Assert.Equals(expected, actual)
End Sub
End Class
结果
调试测试,你会得到这个: InvalidCastException Method invocation failed because 'Public Shared Function WhatIs(thing As stuff.House) As String' 不能用这些参数调用:
参数匹配参数 'thing' 无法从 'Chair' 转换为 'House'。
这些变化使它工作,但为什么呢?!
公开他们
将 HouseExaminer 中的私有共享函数更改为 public,重新运行测试。扰流板,它有效
显式转换对象
将它们改回私有然后替换
isA &= WhatIs(item)
和
If TypeOf item Is Chair Then isA &= WhatIs(CType(item, Chair))
If TypeOf item Is Table Then isA &= WhatIs(CType(item, Table))
重新运行测试,你知道什么,它有效