什么是C#"is"关键字的VB.NET等价物?

Tah*_*aza 43 c# vb.net c#-to-vb.net

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

if (x is IFoo) { }
Run Code Online (Sandbox Code Playgroud)

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

Jar*_*Par 64

请尝试以下方法

if TypeOf x Is IFoo Then 
  ...
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 6

像这样:

If TypeOf x Is IFoo Then
Run Code Online (Sandbox Code Playgroud)


Mar*_*urd 5

直接翻译就是:

If TypeOf x Is IFoo Then
    ...
End If
Run Code Online (Sandbox Code Playgroud)

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

var y = x as IFoo;
if (y != null)
{
   ... something referencing y rather than (IFoo)x ...
}
Run Code Online (Sandbox Code Playgroud)

好的,

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

更好。