TypeOf是myType

时间:2009-12-03 10:25:13

标签: .net vb.net typeof

Public MyObj as Object

Public Function Test(t as Type) as Boolean
 Return TypeOf MyObj is t ' does not work
End Function

感谢。

*编辑

=============================================== =====================

为了清楚起见,我将使用一个完整的例子,最初被认为有点修改。

我使用了一个接口,并且想知道参数中传递的对象(实现I)是否与内部字段相同( I; A:I; AA:A; B:I )。

首先,(a)我需要确切的类别识别(只有 A = A,B = B,AA = AA ) 并且我还希望(b)具有“继承等效”( A = A和A = AA但A<> B

Option Strict On
Option Explicit On

Public Class Form1
  ' object to test
  Private objI As I

  Private Sub Button1_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Button1.Click
    Dim aObj As New A
    Dim aaObj As New AA
    Dim bObj As New B

    'assing the object to test - A
    Me.objI = New A

    'test it
    MessageBox.Show(SameTypeAs(aObj).ToString()) ' need True here
    MessageBox.Show(SameTypeAs(bObj).ToString()) ' need False here
    MessageBox.Show(SameTypeAs(aaObj).ToString()) ' need a)Flase and b)True here
  End Sub

  Function SameTypeAs(ByVal iObj As I) As Boolean
    ' here is the "problem":
    ' how to detect the same (sub)types of I?
    Return Me.objI Is iObj
  End Function

  ' interface..........
  Interface I
  End Interface

  ' class A..........
  Class A
    Implements I
  End Class

  ' class B..........
  Class B
    Implements I
  End Class

  ' class AA..........
  Class AA
    Inherits A
  End Class
End Class

3 个答案:

答案 0 :(得分:5)

您可能希望使用Type.IsAssignableFrom

,而不是比较类型的相等性
return t.IsAssignableFrom(MyObj.GetType())

如果查看TypeOf ... Is ...运算符文档,您会看到它需要类型名称作为第二个操作数。此类型名称在编译时解析。

编辑:如果你真的想要完全相等,那么TypeOf ... Is ...无论如何都不适合你。

至于差异,请考虑:

MyObj = New MemoryStream()

...

Dim result = Test(GetType(Stream))

你想result是真还是假?如果你想要它是假的,你应该使用简单的相等:

return t is MyObj.GetType()

如果您希望它为真,因为MyObj 分配兼容Stream,您应该使用此答案顶部的代码。这将是TypeOf MyObject Is Stream的行为,这就是我最初的答案。

编辑:好的,回答改变的问题:

Function SameTypeAs(ByVal iObj As I) As Boolean
  Return Me.objI.GetType() = iObj.GetType()
End Function

Function CompatibleType(ByVal iObj As I) As Boolean
  Return Me.objI.GetType().IsAssignableFrom(iObj.GetType())
  ' Or this depending on which way round you want compatibility
  ' Return iObj.GetType().IsAssignableFrom(Me.objI.GetType())
End Function

请注意,这不是空的安全 - 如果您传入NothingMe.objI什么都没有,那么您将NullReferenceException调用GetType() }。

答案 1 :(得分:2)

你可以这样做:

Return GetType(MyObj).Equals(t)

答案 2 :(得分:1)

最后,对于a)点我似乎找到了解决方案:

  Function SameTypeAs(ByVal iObj As I) As Boolean
    Return CType(iObj, Object).GetType Is CType(Me.objI, Object).GetType()
  End Function

或通用变体

  Function SameTypeAs(Of T As I)() As Boolean
    Return TypeOf Me.objI Is T
  End Function

至于b)......