VB.NET相当于C#“ As”


79

在VB.NET中,C#As关键字的等效项如下所示?

var x = y as String;
if (x == null) ...

Answers:


102

它是TryCast:

Dim x As String = TryCast(y, String)
If x Is Nothing Then ...

4
+1尽管我认为TryCast这并不完全等同,as因为TryCast不适用于值类型?
MarkJ

7
@Mark:as运算符也不适用于C#中的值类型。
汉斯·帕桑

2
好吧,它适用于可为空的值类型...您可以这样做:var x = y int ?; if(x == null)...因此,您应该能够在VB中执行Dim x = TryCast(y,System.Nullable(Of Integer))
JoelFan 2010年

2
这仅在极少数情况下有效,因为C#自动将装箱转换应用到“ y”。它不能将double转换为int吗?
汉斯·帕桑

1
@HansPassant C#几乎不会“隐式”将一种原始类型(或任何类型)转换为另一种,您可以使用Convert.ToXXX方法
enorl76


6

TryCast:

Dim x = TryCast(y, String)
if (x Is Nothing) ...

5

干得好:

C#代码:

var x = y as String;
if (x == null) ...

相当于VB.NET:

Dim x = TryCast(y, String)
If (x Is Nothing) ...



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.