c# - 空运算符 c#

标签 c# null nullreferenceexception

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 将是输出

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

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% 确保您的对象始终使用某些属性进行初始化,否则您可以替换“旧式”构造函数,例如:

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 };

关于c# - 空运算符 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45840417/

相关文章:

asp.net - SharePoint 2013,自定义 IHttpModule NullReferenceException

c# - Entity Framework .find(id) NullReferenceException

c# - 使用EmguCV在OpenCV中实现push_back

c# - 如何获取 IWindsorContainer 中已注册程序集的列表 (C#)

c# - 增加一个包含字母和数字的字符串

swift - UILabel 返回 "nil"?

c# - 在一定字符数后拆分字符串

java - 如何在类中将实例设置为空?

ios - 如何在 iOS 中检查 NSString 中的 NULL 值?

c# - 将 SqlParameter 添加到 SqlParameterCollection 时出现 NullReferenceException