有人可以解释为什么这在C#.NET 2.0中有效:
Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
......但这不是:
Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
后一种形式给我一个编译错误"无法确定条件表达式的类型,因为'<null>'和'System.DateTime'之间没有隐式转换."
并不是说我不能使用前者,但第二种风格与我的其余代码更加一致.
更新1:
这条线上引发了异常:
client_group_details.Add(new ClientGroupDetails(
Run Code Online (Sandbox Code Playgroud)
原始问题:
我有以下代码,我从数据库的30列数据中删除了数据库中的2列.每当任何列返回NULL值时,我都会收到错误:
public class ClientGroupDetails
{
public String Col2;
public String Col3;
public ClientGroupDetails(String m_Col2, String m_Col3)
{
Col2 = m_Col2;
Col3 = m_Col3;
}
public ClientGroupDetails() { }
}
[WebMethod()]
public List<ClientGroupDetails> GetClientGroupDetails(string phrase)
{
var client_group_details = new List<ClientGroupDetails>();
using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
{
using (command = new SqlCommand(@"select col2, col3 where col1 = @phrase", connection))
{
command.Parameters.Add("@phrase", SqlDbType.VarChar, 255).Value = phrase;
connection.Open();
using (reader = command.ExecuteReader())
{
int Col2Index = reader.GetOrdinal("col2");
int …Run Code Online (Sandbox Code Playgroud)