📜  在C#中是vs As运算符关键字

📅  最后修改于: 2021-05-29 22:47:02             🧑  作者: Mango

isas运算符之间的区别如下:

  • is运算符用于检查对象的运行时类型是否与给定类型兼容,而as运算符用于在兼容的引用类型或Nullable类型之间执行转换。
  • is运算符是布尔类型,而as运算符不是布尔类型。
  • 如果给定对象是同一类型的运算符返回true,而作为运算符返回时,他们与给定类型兼容的对象。
  • is运算符返回false如果给定的对象不是同一类型的,而作为运算符返回NULL如果转换是不可能的。
  • is运算符仅用于引用,装箱和取消装箱转换,而as运算符仅用于可空,引用和装箱转换

的示例是运算符

// C# program to illustrate the
// use of is operator keyword
using System;
  
// taking a class
public class P { }
  
// taking a class
// derived from P
public class P1 : P { }
  
// taking a class
public class P2 { }
  
// Driver Class
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating an instance
        // of class P
        P o1 = new P();
  
        // creating an instance
        // of class P1
        P1 o2 = new P1();
  
        // checking whether 'o1'
        // is of type 'P'
        Console.WriteLine(o1 is P);
  
        // checking whether 'o1' is
        // of type Object class
        // (Base class for all classes)
        Console.WriteLine(o1 is Object);
  
        // checking whether 'o2'
        // is of type 'P1'
        Console.WriteLine(o2 is P1);
  
        // checking whether 'o2' is
        // of type Object class
        // (Base class for all classes)
        Console.WriteLine(o2 is Object);
  
        // checking whether 'o2'
        // is of type 'P'
        // it will return true as P1
        // is derived from P
        Console.WriteLine(o2 is P1);
  
        // checking whether o1
        // is of type P2
        // it will return false
        Console.WriteLine(o1 is P2);
  
        // checking whether o2
        // is of type P2
        // it will return false
        Console.WriteLine(o2 is P2);
    }
}

输出:

True
True
True
True
True
False
False

as运算符的示例:

// C# program to illustrate the
// concept of 'as' operator
using System;
  
// Classes
class Y { }
class Z { }
  
class GFG {
  
    // Main method
    static void Main()
    {
  
        // creating and initializing object array
        object[] o = new object[5];
        o[0] = new Y();
        o[1] = new Z();
        o[2] = "Hello";
        o[3] = 4759.0;
        o[4] = null;
  
        for (int q = 0; q < o.Length; ++q) {
  
            // using as operator
            string str1 = o[q] as string;
  
            Console.Write("{0}:", q);
  
            // checking for the result
            if (str1 != null) {
                Console.WriteLine("'" + str1 + "'");
            }
            else {
                Console.WriteLine("Is is not a string");
            }
        }
    }
}

输出:

0:Is is not a string
1:Is is not a string
2:'Hello'
3:Is is not a string
4:Is is not a string