在C#中使用可空类型和空合并运算符?

时间:2017-06-21 16:00:45

标签: c# linq null-coalescing-operator

在以下关于LINQ Outer Join的MSDN官方文章中,作者在...select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };中一起使用???问题:为什么不将??用作:select new { person.FirstName, PetName = subpet.Name ?? String.Empty };,我认为这会转换为if subpet.Name is null give me empty string。我误解了什么吗?

查询原因:当我在代码中使用???时(解释为hereVS2015智能感知是给我这个错误也在那篇文章中解释过。

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Pet
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

public static void LeftOuterJoinExample()
{
    Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
    Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
    Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
    Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

    Pet barley = new Pet { Name = "Barley", Owner = terry };
    Pet boots = new Pet { Name = "Boots", Owner = terry };
    Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
    Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
    Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

    // Create two lists.
    List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
    List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };

    var query = from person in people
                join pet in pets on person equals pet.Owner into gj
                from subpet in gj.DefaultIfEmpty()
                select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };

    foreach (var v in query)
    {
        Console.WriteLine($"{v.FirstName+":",-15}{v.PetName}");
    }
}

// This code produces the following output:
//
// Magnus:        Daisy
// Terry:         Barley
// Terry:         Boots
// Terry:         Blue Moon
// Charlotte:     Whiskers
// Arlene:

2 个答案:

答案 0 :(得分:1)

你不是误会。由于DefaultIfEmpty()

,程序员正在测试subpet为null

在表达式

    subpet?.Name ?? String.Empty 
  • subpet可以为null,在这种情况下subpet?.Name也为空。
  • String.Empty可缩短为&#34;&#34;

所以要确保非空字符串,

    subpet?.Name ?? ""

答案 1 :(得分:0)

如@Lee所述,<Fraction?>可能为空。因此,在调用subpet时抛出异常.Hence,subpet.Name检查??是否为空,subpet返回调用?属性。< / p>