C#:可空结构的默认文字和类型推断
C#: default literal and type inference on nullable structs
从 C# 7.1 开始,可以使用 default
获取默认值而不指定类型。我今天尝试了一下,发现可空结构和可空值类型的结果有些违反直觉。
[TestFixture]
public class Test
{
private class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
[Test]
public void ShouldBehaveAsExpected()
{
var person1 = new Person {Name = "John", Age = 58};
var person2 = new Person {Name = "Tina", Age = 27};
var persons = new[] {person1, person2};
int? myAge = persons.FirstOrDefault(p => p.Name == "MyName")?.Age;
var myDefaultAge = myAge ?? default;
var myAgeString = myAge == null ? "null" : myAge.ToString();
var myDefaultAgeString = myDefaultAge == null ? "null" : myDefaultAge.ToString();
Console.WriteLine("myAge: " + myAgeString); // "myAge: null"
Console.WriteLine("myDefaultAge: " + myDefaultAgeString); // "myDefaultAge: 0"
}
}
我本以为 myDefaultAge
是 null
而不是 0
,因为 myAge 是 int?
类型而 default(int?)
是 null
].
是否在任何地方指定了此行为? C# programming guide 仅表示“默认文字产生与等效默认值 (T) 相同的值,其中 T 是推断类型。”
The type of the expression a ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type
准确描述了我们这里的情况 - A
可以为 null,default
没有类型。
从 C# 7.1 开始,可以使用 default
获取默认值而不指定类型。我今天尝试了一下,发现可空结构和可空值类型的结果有些违反直觉。
[TestFixture]
public class Test
{
private class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
[Test]
public void ShouldBehaveAsExpected()
{
var person1 = new Person {Name = "John", Age = 58};
var person2 = new Person {Name = "Tina", Age = 27};
var persons = new[] {person1, person2};
int? myAge = persons.FirstOrDefault(p => p.Name == "MyName")?.Age;
var myDefaultAge = myAge ?? default;
var myAgeString = myAge == null ? "null" : myAge.ToString();
var myDefaultAgeString = myDefaultAge == null ? "null" : myDefaultAge.ToString();
Console.WriteLine("myAge: " + myAgeString); // "myAge: null"
Console.WriteLine("myDefaultAge: " + myDefaultAgeString); // "myDefaultAge: 0"
}
}
我本以为 myDefaultAge
是 null
而不是 0
,因为 myAge 是 int?
类型而 default(int?)
是 null
].
是否在任何地方指定了此行为? C# programming guide 仅表示“默认文字产生与等效默认值 (T) 相同的值,其中 T 是推断类型。”
The type of the expression a ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type
准确描述了我们这里的情况 - A
可以为 null,default
没有类型。