代码之家  ›  专栏  ›  技术社区  ›  Tahbaza

vb.net与“is”关键字的等价物是什么?

  •  40
  • Tahbaza  · 技术社区  · 15 年前

    我需要检查一个给定的对象是否实现了一个接口。在C中,我只想说:

    if (x is IFoo) { }
    

    正在使用 TryCast() 然后检查 Nothing 最好的方法是什么?

    3 回复  |  直到 10 年前
        1
  •  60
  •   JaredPar    15 年前

    尝试以下操作

    if TypeOf x Is IFoo Then 
      ...
    
        2
  •  6
  •   SLaks    15 年前

    这样地:

    If TypeOf x Is IFoo Then
    
        3
  •  1
  •   Mark Hurd    10 年前

    直接翻译为:

    If TypeOf x Is IFoo Then
        ...
    End If
    

    但是(为了回答你的第二个问题)如果原始代码更好地写为

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

    然后,是的,

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

    更好。