c# - 为什么在采用对象初始化器时使用 (int?) null?

标签 c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class User
    {
        public int? Age { get; set; }
        public int? ID { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            User user = new User();
            user.Age = null;        // no warning or error
            user.ID  = (int?)null;  // no warning or error

            string result = string.Empty;
            User user2 = new User
                             {
                Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result),
                // Error    1   Type of conditional expression cannot be determined 
                // because there is no implicit conversion between '<null>' and 'int'   
                // ConsoleApplication1\ConsoleApplication1\Program.cs   23  71  ConsoleApplication1

                ID = string.IsNullOrEmpty(result) ? (int?)null : Int32.Parse(result) // // no warning or error
                             };
        }
    }
}

问题:

为什么下一行不起作用?

Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result)

//更正一是

Age = string.IsNullOrEmpty(result) ? (int?) null : Int32.Parse(result)

为什么下面的行有效?

user.Age = null;        // no warning or error

最佳答案

这是因为三元运算符需要返回类型是相同的类型。

在第一种情况下,“null”可以是任何引用类型(不仅仅是 int?)的 null,因此为了使其对编译器显式,它需要转换。

否则你可以拥有

string x = null;
Age = string.IsNullOrEmpty(result) ? x: Int32.Parse(result)

这显然有点布谷鸟。

关于c# - 为什么在采用对象初始化器时使用 (int?) null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6551601/

相关文章:

c# - 在 MVVM 中使用 CommandParameter 传递类变量

c# - 创建文件作为流并上传到 Azure

c# - Linq 对列表使用 Aggregate()

c# - 将 2 个列表合并到一个新列表中,该列表包含列表 1 和列表 2 中的数据 - 其中唯一键为 "VariantId"

c# - SVCUTIL.EXE:有什么方法可以分离我的 Commons.xsd 类? (C#)

c# - 为什么这个并行代码比类似的非并行版本慢?

c# - 如何以提升的权限运行 wpf 应用程序?

c# - RegLoadAppKey 在 32 位操作系统上运行良好,在 64 位操作系统上失败,即使两个进程都是 32 位的

C# 使用 lambda 表达式委托(delegate)逆变

c# - 创建对 IObservable 的弱订阅