as 运算符用于执行可兼容类型之间的转换。as 运算符用在以下形式的表达式中:
as 运算符类似于类型转换,所不同的是,当转换失败时,as 运算符将产生空,而不是引发异常。在形式上,这种形式的表达式:
expression as type
等效于:
expression is type ? (type)expression : (type)null
只是 expression 只被计算一次。
请注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来代替其执行。
' Visual Basic
Private Sub TextBox1_Validating(ByVal Sender As Object, ByVal e As CancelEventArgs) Handles TextBox1.Validating
If Not IsNumeric(TextBox1.Text) Then
ErrorProvider1.SetError (TextBox1, "Not a numeric value.")
Else
' Clear the error.
ErrorProvider1.SetError (TextBox1, "")
End If
End Sub
// C#
protected void textBox1_Validating (object sender, CancelEventArgs e)
{
try
{
int x = Int32.Parse(textBox1.Text);
errorProvider1.SetError(textBox1, "");
}
catch
{
errorProvider1.SetError(textBox1, "Not an integer value.");
}
}