Talk about the type conversion operator is and as

  • 2020-05-30 19:48:44
  • OfStack

1. The introduction
Type safety is one of the key considerations at the beginning of the design of NET. For programmers, it is often difficult to fully grasp the type safety of system data. Now, this one has been solved for you in Microsoft's design framework. In.NET, the 1-cut type must be integrated from the System.Object type, so we can easily get the exact type of the object by using the GetType() method. So what are some of the things you should think about in NET for type conversion?
2. Concept introduction
Type conversion includes display conversion and implicit conversion, and the basic rules for type conversion in.NET are as follows:
Any type can be safely converted to its base class type, which can be done by implicit conversion.
When any type is converted to its derived type, a display conversion must be performed under the following rules :(type name) object name;
You can get the exact type of any object using GetType.
Base types can be converted using the Covert class.
All types other than string have the Parse method, which converts a string type to its base type.
The conversion mechanisms for value types and reference types are called boxing (boxing) and unboxing (unboxing).
3. Principles and examples
It is time to focus on the envailing of is and as operators. Type conversion will be a larger topic and will be discussed at the appropriate time.
The is/as operator, which is used for type conversion in C#, provides a determination of type compatibility, thus making the type conversion control safe and providing flexible type conversion control.

The rules of is are as follows:
Check object type compatibility and return the result, true or false;
If the object is null, the return value is always false.


namespace Learning
{
    public partial class check : System.Web.UI.Page
    {
        object o = new object();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(o.GetType());//System.Object
            if (o is System.Object)  // The first 1 Subtype compatibility check, o is A  return false
            {
                Response.Write("o is System.Object");
            }
        }
    }
}

The rules of as are as follows:
Check the compatibility of the object type and return the result, if not, null.
If the result is judged to be empty, an NullReferenceException exception is thrown when the type conversion is enforced.


namespace Learning
{
    public partial class check : System.Web.UI.Page
    {
        object o = new object();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(o.GetType());//System.Object
            if ((o as System.Object)!=null)  // The first 1 Subtype compatibility check, o is A  return false
            {
                Response.Write("o is System.Object");
            }
        }
    }
}


Related articles: