【发布时间】:2011-03-11 04:42:31
【问题描述】:
我需要检查给定对象是否实现了接口。在 C# 中我会简单地说:
if (x is IFoo) { }
使用TryCast() 然后检查Nothing 是最好的方法吗?
【问题讨论】:
标签: c# vb.net c#-to-vb.net
我需要检查给定对象是否实现了接口。在 C# 中我会简单地说:
if (x is IFoo) { }
使用TryCast() 然后检查Nothing 是最好的方法吗?
【问题讨论】:
标签: c# vb.net c#-to-vb.net
试试下面的
if TypeOf x Is IFoo Then
...
【讨论】:
像这样:
If TypeOf x Is IFoo Then
【讨论】:
直接翻译为:
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
更好。
【讨论】: