2017-08-23 172 views
2

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.Namenulldog.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); 
    } 
} 

没有得到错误,如果fapnull

我们如何能够用同样的方式执行类似实现?

+1

'''fap.Name => FAP .Name' '' – tym32167

+4

'fap?.Name ?? dog.Name' – TryingToImprove

+0

谢谢,@TryingToImprove –

回答

7

使用C#6.0 Null propagation:(?)(?[)

用来测试空执行成员访问或索引之前操作

所以:

Console.WriteLine(fap?.Name ?? dog.Name); 

在旁注:除非你想确保100%你的对象总是initiali ZED与某些属性可以取代 “旧风格” 的构造函数,例如:

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

谢谢!我必须等待10分钟才能接受你的答案,我正在寻找一种方法来避免if(fap!= null)的使用,你只是给了我一种用我最喜欢的语言编程时感觉更好的方式! –

+0

@MarcoSalerno - 欢迎您:)雅!这个功能是非常需要的,使用起来很有趣 –

+1

是的,我不知道存在,我会用它很多! –