空运算符 c#

Null operators c#

c#中我们可以像这样使用??运算符:

class Program
{
    static void Main(string[] args)
    {
        Dog fap = new Dog("Phon", Sex.Male);
        Dog dog = new Dog("Fuffy", Sex.Male);
        Console.WriteLine(fap.Name ?? dog.Name);
    }
}

class Dog : IAnimal
{
    public Dog(string name, Sex sex)
    {
        this.Name = name;
        this.Sex = sex;
    }

    public string Name { get; set; }
    public Sex Sex { get; set; }

    public void Attack()
    {
        throw new NotImplementedException();
    }

    public void Eat()
    {
        throw new NotImplementedException();
    }

    public void Sleep()
    {
        throw new NotImplementedException();
    }
}

interface IAnimal
{
    string Name { get; set; }

    Sex Sex { get; set; }

    void Eat();

    void Attack();

    void Sleep();
}

enum Sex
{
    Male,
    Female,
    Unknown
}

这样,如果 fap.Namenulldog.Name 将是 output

我们如何使用相同的实现方式实现类似的东西:

class Program
{
    static void Main(string[] args)
    {
        Dog fap = null;
        Dog dog = new Dog("Fuffy", Sex.Male);
        Console.WriteLine(fap.Name ?? dog.Name);
    }
}

如果 fapnull 则不会出现错误?

使用 C# 6.0 Null propagation:

Used to test for null before performing a member access (?.) or index (?[) operation

所以:

Console.WriteLine(fap?.Name ?? dog.Name);

旁注:除非您想 100% 确保您的对象始终使用某些属性进行初始化,否则您可以替换 "old style" 构造函数,例如:

public Dog(string name, Sex sex)
{
    // Also if property names and input variable names are different no need for `this`
    this.Name = name; 
    this.Sex = sex;
}

仅使用对象初始化语法:

Dog dog = new Dog { Name = "Fuffy" , Sex = Sex.Male };