C# as operator

as operator 係用黎做 casting 的

static void Main()
{
    double x = 1234.7;
    int a;
    // Cast double to int.
    a = (int)x;
    System.Console.WriteLine(a);
}
// Output: 1234

如果用 boxing 黎轉 type 既話, 錯 type 的話就會 throw InvalidCastException, 但如果用 as operator 就唔會 throw InvalidCastException, 而 value 就會係 null

public static void Main()
{
    object time1 = DateTime.Now;
    DateTime? t = time1 as DateTime?;    // valid casting
    int? wrongCast = time1 as int?;    // wrongCast == null
}

Tags:

Leave a Reply

You must be logged in to post a comment.