What is a difference between casts: (A) x and x as A?

This question already has an answer here:

  • Direct casting vs 'as' operator? 15 answers
  • Casting vs using the 'as' keyword in the CLR 18 answers
  • What is the difference between casting and using “as” in C#? 8 answers

  • The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.

    You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.

    Consider the following example:

    expression as type
    

    The code is equivalent to the following expression except that the expression variable is evaluated only one time.

    expression is type ? (type)expression : (type)null
    

    Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

    Refer: as (C# Reference)


    By doing (A)x you are doing a cast which will definatly try and cast, if it can't cast there will be an exception.

    If you use as it will either cast or be null .

    However, you have all the example code you need to try this yourself so you could of potentially tried this before asking us what the code you have stated is going to do.


    第一个试图立即转换,第二个实际检查x是否是A型。

    链接地址: http://www.djcxy.com/p/73742.html

    上一篇: 何时使用“as”关键字以及何时使用()铸造?

    下一篇: 演员之间有什么区别:(A)x和x是A?