as 与 is 运算符

+ as与is运算符
  1. is:检查一个对象是否兼容于其他指定的类型,并返回一个 Bool 值,不会抛出异常.
  2. as: 与强制类型转换是一样的,如果转换不成功,会返回null,不会抛出异常.
  3. is 和 as运算符只能用于引用转换以及装箱和拆箱转换,不能用于用户自定义转换.
is运算符
as运算符
using System;

class Employee : Persion {}

class Persion {
    public string Name = "Employee";
    public int Age = 25;
}

class Program
{
    static void Main(string[] args)
    {
        Employee bill = new Employee();
        if (bill is Persion) {
            Persion p = bill;
            Console.WriteLine($"Person {p.Name}, {p.Age}");
        }
    }   
}
using System;

class Employee : Persion {}

class Persion {
    public string Name = "Employee";
    public int Age = 25;
}

class Program
{
    static void Main(string[] args)
    {
        Employee bill = new Employee();
        Persion p;
        p = bill as Persion;
        if (p != null) {
            Console.WriteLine($"Persion: {p.Name},{p.Age}");
        }
    }   
}

?. 与 ?? 与 ?[] 运算符

+ ?. 与 ??
  1. ??: 如果此运算符的左操作数不为 null,则此运算符将返回左操作数,否则返回右操作数.
  2. ?.: 如果对象为 NULL, 则不进行后面的获取成员的运算, 直接返回NULL.
??运算符
?.运算符
using System;

class Program
{
    static void Main()
    {
        string name = null;

        // 使用??运算符来处理空引用的情况
        string result = name ?? "DefaultName";

        Console.WriteLine("Name: " + result);
    }
}
using System;

class Person
{
  private string m_Name;
  public string Name {
    set {
      m_Name = value;
    }
    get {
      return m_Name;
    }
  }
}

class Program
{
    static void Main()
    {
        Person person = new Person();
        person.Name = "yhj";
        
        // 使用?.运算符来安全地访问可能为空的对象的属性
        string name = person?.Name;
        Console.WriteLine(name);

        if (name == null)
        {
            Console.WriteLine("Person对象为null");
        }
        else
        {
            Console.WriteLine("Person的名字是: " + name);
        }
    }
}

在线测试

+ 在线测试