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
};
}
}
}
問:爲什麼在採用對象初始值設定項時使用(int?)null?
爲什麼下面的行不行?
Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result)
//糾正一個是
Age = string.IsNullOrEmpty(result) ? (int?) null : Int32.Parse(result)
爲什麼下面這行工作?
user.Age = null; // no warning or error
查看http://stackoverflow.com/questions/1171717 –