What is the VB.NET equivalent of the C# “is” keyword?

后端 未结 3 2006
终归单人心
终归单人心 2020-12-15 15:03

I need to check if a given object implements an interface. In C# I would simply say:

if (x is IFoo) { }

Is using a TryCast() a

相关标签:
3条回答
  • 2020-12-15 15:35

    The direct translation is:

    If TypeOf x Is IFoo Then
        ...
    End If
    

    But (to answer your second question) if the original code was better written as

    var y = x as IFoo;
    if (y != null)
    {
       ... something referencing y rather than (IFoo)x ...
    }
    

    Then, yes,

    Dim y = TryCast(x, IFoo)
    If y IsNot Nothing Then
       ... something referencing y rather than CType or DirectCast (x, IFoo)
    End If
    

    is better.

    0 讨论(0)
  • 2020-12-15 15:38

    Try the following

    if TypeOf x Is IFoo Then 
      ...
    
    0 讨论(0)
  • 2020-12-15 15:40

    Like this:

    If TypeOf x Is IFoo Then
    
    0 讨论(0)
提交回复
热议问题