【问题标题】:C# Nullable Ints - Compile ErrorC# Nullable Ints - 编译错误
【发布时间】:2015-02-04 04:50:59
【问题描述】:

为什么

            int? nullInt = null;
            base.Response.Data = (new BusinessLogic.RefDataManager(base.AppSettingsInfo)).SelectAppData(new DC.AppData() { AppDataKey = app_data_key != string.Empty ? app_data_key : null, AppDataTypeId = app_data_type_id != string.Empty ? int.Parse(app_data_type_id) : nullInt });

编译,但是这个

            base.Response.Data = (new BusinessLogic.RefDataManager(base.AppSettingsInfo)).SelectAppData(new DC.AppData() { AppDataKey = app_data_key != string.Empty ? app_data_key : null, AppDataTypeId = app_data_type_id != string.Empty ? int.Parse(app_data_type_id) : null});

没有?第二条语句的编译错误是“无法确定条件表达式的类型,因为'int'和null之间没有隐式转换”

DC.AppData 是

public class AppData
{
    [DataMember(Name = "AppDataKey")]
    public string AppDataKey { get; set; }

    [DataMember(Name = "AppDataTypeId")]
    public int? AppDataTypeId { get; set; }


}

【问题讨论】:

  • 为什么要把所有这些都塞在一行上,如果你只使用多行,它会更具可读性,而且你不会遇到这样的问题。

标签: c# nullable


【解决方案1】:

C# 中的三元运算符不相信您将null 表示为int?。您必须明确告诉 C# 编译器您的意思是 nullint?...

base.Response.Data = (new BusinessLogic.RefDataManager(base.AppSettingsInfo)).SelectAppData(new DC.AppData() { AppDataKey = app_data_key != string.Empty ? app_data_key : null, AppDataTypeId = app_data_type_id != string.Empty ? int.Parse(app_data_type_id) : (int?)null});

...或者 int.Parse(app_data_type_id)int? 通过强制转换...

(int?)int.Parse(app_data_type_id)

任何一个三元 yield 操作数都必须显式转换为 int?

【讨论】:

    【解决方案2】:

    问题出在这里:

    app_data_type_id != string.Empty ? int.Parse(app_data_type_id) : null
    

    int.Parse 返回一个不可为空的 int

    您需要将其转换为 int 吗?

    (int?) int.Parse(app_data_type_id) : null
    

    【讨论】:

    • 实际上,我们的两个答案都提供了一个可行的解决方案。似乎任何一个三元 yield 操作数都需要显式为 int?,但不能同时为两者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多