gpt4 book ai didi

c# - 空运算符 c#

转载 作者:行者123 更新时间:2023-11-30 20:17:13 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com