在 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.Name
是 null
,dog.Name
将是输出
。
我们如何使用相同的实现方式实现类似的东西:
class Program
{
static void Main(string[] args)
{
Dog fap = null;
Dog dog = new Dog("Fuffy", Sex.Male);
Console.WriteLine(fap.Name ?? dog.Name);
}
}
如果 fap
为 null
不会出错?
最佳答案
使用 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/