在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
将是output
。
我们如何以相同的实现方式实现如下:
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
所以:
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 };