gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:03:09 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com