在下面的MSDN官方文章LINQ Outer Join中,作者正在使用?和??一起在...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
。我误解了什么吗?在C#中使用可空类型和空合并运算符?
原因的调查:当我在我的代码使用?
和??
在一起(解释here)的VS2015
智能感知是给我的错误在该职位还解释。
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:
如果'subpet'是空'subpet.Name'将抛出。 – Lee
'subpet?.Name ??无论'subpet'为null还是'subpet.Name'为null,String.Empty'都会评估为空字符串 –
@SirRufo我的困惑是由于我在其中一个代码中出现的错误, ://stackoverflow.com/q/44681362/1232087)。但我认为'@ JonSkeet'和'@ hvd'已在该帖子中解释过。 – nam