在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.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
:
我们如何能够用同样的方式执行类似实现?
'''fap.Name => FAP .Name' '' – tym32167
'fap?.Name ?? dog.Name' – TryingToImprove
谢谢,@TryingToImprove –