c # - is as operator and

  A, IS operator for determining whether an object can be converted to the specified type, no exception is thrown, bool return value to indicate whether the conversion is successful:

if (myObj is MyClass)
{
    //do...
}

  When the conversion is successful meet any of the following circumstances:

  1. Conversion object is an instance of the target type;

  2. The conversion from the target object is an instance of a derived type type;

  3. Conversion object is an implementation example of the type of the target interface;

  Mode is supported in C # 7.0 or later and switch the match expression pattern matching expression;

  Two, as operator with a similar cast, but will not throw an exception if the conversion is unsuccessful, it will return null, is usually used in conjunction with sentence air operations:

MyClass myObj = obj as MyClass;
if (myObj != null)
{
    //do...
}

  Only 1.as operator (if the original object and the target type is a value type is a reference type, the target type can be used to successfully convert a reference type or nullable type conversion operator, generally does not create new objects in the conversion will produce packing operation, a new object); for certain types of non-nullable type value types can be used with the cast is operator conversion:

if (myObj is int)
{
    int myNum = (int)myObj;
    //do...
}

  ※ generics, if required as operators convert the object type parameter type, it is necessary to add a base class or class type constraint constraints:

WHERE T: BaseClass // specify a base class constraints 
WHERE T: class  // specified class type constraint

  When 2.is as operator and will not perform a custom type conversion (in this case should use a cast), the type thereof only when the operation is switched in line with the target objects when the type conversion rules (i.e., above situations) to conversion successful;

  ※ compared to the cast, it should be used as much as possible as operator, since as operators convert safer and more efficient;

 


If you feel that you have read this article to help, please click the "recommend" button, your recognition is the greatest power of my writing!

Author: Minotauros
Source: https://www.cnblogs.com/minotauros/

This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise the right to pursue legal responsibilities.

Guess you like

Origin www.cnblogs.com/minotauros/p/11614106.html
Recommended