Toán tử as thực hiện chuyển đổi kiểu an toàn giữa các kiểu tương thích. Trả về null nếu chuyển đổi thất bại (thay vì ném exception như cast (Type)obj).
Chỉ dùng cho: reference conversion, nullable conversion, boxing conversion. Không dùng cho user-defined conversion.
Cú pháp:
string s = obj as string; // null nếu obj không phải string
Ví dụ
using System;
public class Demo
{
public static void Main()
{
object[] obj = new object[2];
obj[0] = "jack";
obj[1] = 32;
for (int i = 0; i < obj.Length; ++i)
{
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("This is not a string!");
}
Console.ReadKey();
}
}
Kết quả
0: 'jack'
1: This is not a string!
So sánh:
| Cast (Type)obj | as Type |
|---|---|
| Ném InvalidCastException nếu fail | Trả về null nếu fail |
| Dùng cho mọi conversion | Chỉ reference/nullable/boxing |
| Phải try-catch | Kiểm tra null |