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

此生再无相见时 提交于 2019-11-27 21:30:54

问题


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() and then checking for Nothing the best way?


回答1:


Try the following

if TypeOf x Is IFoo Then 
  ...



回答2:


Like this:

If TypeOf x Is IFoo Then



回答3:


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.



来源:https://stackoverflow.com/questions/3167479/what-is-the-vb-net-equivalent-of-the-c-sharp-is-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!