zoukankan      html  css  js  c++  java
  • as 运算符

    as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而非引发异常。

    as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用强制转换表达式来执行。

    expression as type
    等效于(但只计算一次 expression)
     
    expression is type ? (type)expression : (type)null

    as 运算符用于在兼容的引用类型之间执行转换。例如:
    // cs_keyword_as.cs
    // The as operator.
    using System;
    class Class1
    {
    }

    class Class2
    {
    }

    class MainClass
    {
        static void Main()
        {
            object[] objArray = new object[6];
            objArray[0] = new Class1();
            objArray[1] = new Class2();
            objArray[2] = "hello";
            objArray[3] = 123;
            objArray[4] = 123.4;
            objArray[5] = null;

            for (int i = 0; i < objArray.Length; ++i)
            {
                string s = objArray[i] as string;
                Console.Write("{0}:", i);
                if (s != null)
                {
                    Console.WriteLine("'" + s + "'");
                }
                else
                {
                    Console.WriteLine("not a string");
                }
            }
        }
    }
    //=============================================================//
    0:not a string
    1:not a string
    2:'hello'
    3:not a string
    4:not a string
    5:not a string

  • 相关阅读:
    十大经典排序算法
    Redis 实现消息队列 MQ
    Memcache/Memcached的PHP操作手册(纯手稿版)
    PHP 共享内存使用与信号控制
    WebSocket和Socket的区别
    电商平台系统架构设计案例分析
    电商网站架构案例
    大型网站架构系列:电商网站架构案例
    电商峰值系统架构设计--转载
    IT系统
  • 原文地址:https://www.cnblogs.com/rohelm/p/2384109.html
Copyright © 2011-2022 走看看