C#:默认文字和可空结构的类型推断 [英] C#: default literal and type inference on nullable structs

查看:61
本文介绍了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."

推荐答案

表达式的类型??b取决于操作数上可用的隐式转换.按照优先顺序,类型为??.b是A0,A或B,其中A是a的类型(假设a具有类型),B是b的类型(假设b具有类型),并且A0是A的基础类型(如果A是可以为空的类型

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 可为空, default 没有类型.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆