zoukankan      html  css  js  c++  java
  • C# IS 和 AS 的用法和区别

    is和as都是在类型转换时常用到得,并且提供的对象可以强制转换为所提供的类型而不会导致引发异常。

    IS

    请注意,is 运算符只考虑引用转换、装箱转换和取消装箱转换。 不考虑其他转换,如用户定义的转换。

    is 运算符的左侧不允许使用匿名方法。 lambda 表达式属于例外。

    is判断返回值是true或者是false

     1 class Class1 {}
     2 class Class2 {}
     3 class Class3 : Class2 { }
     4 
     5 class IsTest
     6 {
     7     static void Test(object o)
     8     {
     9         Class1 a;
    10         Class2 b;
    11 
    12         if (o is Class1)
    13         {
    14             Console.WriteLine("o is Class1");
    15             a = (Class1)o;
    16             // Do something with "a."
    17         }
    18         else if (o is Class2)
    19         {
    20             Console.WriteLine("o is Class2");
    21             b = (Class2)o;
    22             // Do something with "b."
    23         }
    24 
    25         else
    26         {
    27             Console.WriteLine("o is neither Class1 nor Class2.");
    28         }
    29     }
    30     static void Main()
    31     {
    32         Class1 c1 = new Class1();
    33         Class2 c2 = new Class2();
    34         Class3 c3 = new Class3();
    35         Test(c1);
    36         Test(c2);
    37         Test(c3);
    38         Test("a string");
    39     }
    40 }
    41 /*
    42 Output:
    43 o is Class1
    44 o is Class2
    45 o is Class2
    46 o is neither Class1 nor Class2.
    47 */

    AS

    as 运算符用于在兼容的引用类型之间执行某些类型的转换,as 运算符类似于强制转换操作。 但是,如果无法进行转换,则 as 返回 null。

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

    as判断返回值是某个类型或者是null

     1 class ClassA { }
     2 class ClassB { }
     3 
     4 class MainClass
     5 {
     6     static void Main()
     7     {
     8         object[] objArray = new object[6];
     9         objArray[0] = new ClassA();
    10         objArray[1] = new ClassB();
    11         objArray[2] = "hello";
    12         objArray[3] = 123;
    13         objArray[4] = 123.4;
    14         objArray[5] = null;
    15 
    16         for (int i = 0; i < objArray.Length; ++i)
    17         {
    18             string s = objArray[i] as string;
    19             Console.Write("{0}:", i);
    20             if (s != null)
    21             {
    22                 Console.WriteLine("'" + s + "'");
    23             }
    24             else
    25             {
    26                 Console.WriteLine("not a string");
    27             }
    28         }
    29     }
    30 }
    31 /*
    32 Output:
    33 0:not a string
    34 1:not a string
    35 2:'hello'
    36 3:not a string
    37 4:not a string
    38 5:not a string
    39 */

    内容中大部分来自msdn

     

  • 相关阅读:
    AD 文档信息设置和制作模板
    用AT命令调试调制解调器
    语音AT命令参考
    传真AT指令部分(参考)
    传真调制解调器
    knockout+weui+zepto
    20171028随手记
    20171027随记
    一些简单又坑人的无聊使用
    ReadWrite,日志,输入文本
  • 原文地址:https://www.cnblogs.com/xiaoch/p/2491597.html
Copyright © 2011-2022 走看看