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

Use of nullable types and null-coalescing operator together in C#?

在下面的MSDN官方文章中LINQ Outer Join, author(s) are using ? and ??一起在...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。我是不是误会了什么?

查询原因:当我在我的代码中同时使用???时(解释VS2015 Intellisense 给我的错误也在 post.

中解释
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:

如@Lee 所述,subpet 可能为空。因此,在调用 subpet.Name 时抛出一个 exception.Hence,?? 检查 subpet 是否为空,然后 ? 返回到调用 .Name 属性.

你没有误会。程序员正在测试 subpet 是否为空,因为 DefaultIfEmpty()

表达式中

    subpet?.Name ?? String.Empty 
  • subpet 可以为空,在这种情况下 subpet?.Name 也为空。
  • String.Empty可以简写为“”

所以为了确保非空字符串,

    subpet?.Name ?? ""