1

매개 변수 중 하나가 인터페이스 인 경우 Visual Studio에서 형식 검사 함수 매개 변수를 중지 한 것처럼 보입니다. 유형 검사 문제의 예 여기VB.Net의 함수 인터페이스 매개 변수로 형식 검사 재미

' An interface and the class that implements it: 
Public Interface IA 

End Interface 

Public Class A 
    Implements IA 
End Class 


' Another reference type for the demonstration: 
Public Class MyReferenceType 

End Class 


' A function that uses IA as the type of one of its parameters: 
Private Function SomeFunc(ByVal a As IA, ByVal r As MyReferenceType) 
    Return Nothing 
End Sub 

을 그리고 :

다음과 같은 고려 내 의견을 제안

Private Sub Example() 
    Dim a As IA = New A 
    Dim r As New MyReferenceType 

    ' Some other random reference type, choose any 
    ' other reference type you like 
    Dim list As New List(Of String) 

    ' Each of these calls to SomeFunc compile without errors. 
    SomeFunc(r, r) 
    SomeFunc(r, a) 
    SomeFunc(list, r) 
    SomeFunc(list, a) 

    ' Does not compile due to type mismatch 
    'SomeFunc(list, list) 
End Sub 

,이 코드 중 하나 편집기에서 오류없이 잘 컴파일 . 프로그램을 실행해도 System.InvalidCastException이 나오는데 놀랍지 않습니다. 나는 이것이 컴파일러에서 타입 검사 버그라고 생각한다. Visual Studio 2005를 사용하고 있습니다.이 버전의 VS가 수정 되었습니까?

답변

1

나는 당신이 Option Strict을 가지고 있기 때문에 그것이라고 생각합니다. Option Strict를 on으로 설정하면 코드가 제대로 컴파일되지 않습니다.

SomeFunc(list, a) 

이처럼되지 않습니다 :이 것을

주 첫 번째 경우에

SomeFunc(list, list) 

, 엄격한 옵션이 꺼져있을 때, 컴파일러는 효과적으로 당신을위한 캐스트를 삽입한다. 결국 IA의 값은MyReferenceType이 될 수 있습니다. 두 번째 경우

, List(Of String)의 값은 지금까지 너무도 옵션 엄격한 오프로 ( Nothing ... 값의 논증 제외) MyReferenceType와 호환되지 않을 수는 컴파일이 실패합니다. 컴파일러는 결코 작동하지 못하는 무언가를 시도하게하지 않습니다.

이야기의 도덕 : 더 나은 유형 확인을 위해 옵션을 엄격하게 설정합니다.

+0

정확합니다! 어떻게 든 Option Strict를 해제해야합니다. MSDN은 기본 상태가 켜져 있다고 말합니다. – AuGambit