What's the point of “As” keyword in C#

后端 未结 7 1203
误落风尘
误落风尘 2020-12-13 01:32

From the docs:

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an exp

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 02:21

    Maybe examples will help:

    // Regular casting
    Class1 x = new Class1();
    Class2 y = (Class2)x; // Throws exception if x doesn't implement or derive from Class2
    
    // Casting with as
    Class2 y = x as Class2; // Sets y to null if it can't be casted.  Does not work with int to short, for example.
    
    if (y != null)
    {
      // We can use y
    }
    
    // Casting but checking before.
    // Only works when boxing/unboxing or casting to base classes/interfaces
    if (x is Class2)
    {
      y = (Class2)x; // Won't fail since we already checked it
      // Use y
    }
    
    // Casting with try/catch
    // Works with int to short, for example.  Same as "as"
    try
    {
      y = (Class2)x;
      // Use y
    }
    catch (InvalidCastException ex)
    {
      // Failed cast
    }
    

提交回复
热议问题