默认文字和可空结构的类型推断

默认文字和可空结构的类型推断

本文介绍了C#:默认文字和可空结构的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从C#7.1开始,可以通过使用 default 来获取默认值,而无需指定类型.我今天尝试了一下,发现可为空的结构和可为空的值类型的结果有些违反直觉.

Since C# 7.1, it is possible to get default values by using default without specifying the type. I tried it out today and found the results for nullable structs and nullable value types somewhat counterintuitive.

[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 .

I would have expected myDefaultAge to be null rather than 0, because myAge is of type int? and default(int?) is null.

此行为是否在任何地方指定? C#编程指南只说默认文字与等效的default(T)产生相同的值,其中T是推断的类型."

Is this behaviour specified anywhere? The C# programming guide only says that " The default literal produces the same value as the equivalent default(T) where T is the inferred type."

推荐答案

空-coalescing运算符:

此处准确地描述了我们的情况- A 可为空, default 没有类型.

Precisely describes our situation here - A is nullable, default doesn't have a type.

这篇关于C#:默认文字和可空结构的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:57