【问题标题】:What is the VB.NET equivalent of the C# "is" keyword?C#“is”关键字的 VB.NET 等效项是什么?
【发布时间】:2011-03-11 04:42:31
【问题描述】:

我需要检查给定对象是否实现了接口。在 C# 中我会简单地说:

if (x is IFoo) { }

使用TryCast() 然后检查Nothing 是最好的方法吗?

【问题讨论】:

    标签: c# vb.net c#-to-vb.net


    【解决方案1】:

    试试下面的

    if TypeOf x Is IFoo Then 
      ...
    

    【讨论】:

      【解决方案2】:

      像这样:

      If TypeOf x Is IFoo Then
      

      【讨论】:

        【解决方案3】:

        直接翻译为:

        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
        

        更好。

        【讨论】:

          猜你喜欢
          • 2010-12-29
          • 1970-01-01
          • 1970-01-01
          • 2011-01-15
          • 2012-10-08
          • 2023-03-12
          • 2011-01-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多