C# Nullable Ints - ข้อผิดพลาดในการคอมไพล์

ทำไมไม่

            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; }


}

person Scott    schedule 04.02.2015    source แหล่งที่มา
comment
ทำไมต้องอัดทั้งหมดนั้นไว้ในบรรทัดเดียว หากคุณใช้หลายบรรทัดก็จะอ่านได้ง่ายขึ้นและคุณไม่มีปัญหาเช่นนี้   -  person Scott Chamberlain    schedule 04.02.2015


คำตอบ (2)


ตัวดำเนินการแบบไตรภาคใน C# ไม่เชื่อใจให้คุณหมายถึง null เป็น int? คุณต้องบอกคอมไพเลอร์ C# อย่างชัดเจนว่าคุณหมายถึง null เป็น int?...

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)

ตัวถูกดำเนินการผลตอบแทนแบบไตรภาคตัวใดตัวหนึ่งจะต้องแปลงเป็น int? อย่างชัดเจน

person Nick Strupat    schedule 04.02.2015

ปัญหาอยู่ที่นี่:

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
person bluetoft    schedule 04.02.2015
comment
จริงๆ แล้ว คำตอบของเราทั้งสองมีวิธีแก้ปัญหาที่ใช้งานได้ ดูเหมือนว่าตัวถูกดำเนินการผลตอบแทนแบบไตรภาคตัวใดตัวหนึ่งจะต้องระบุ int? อย่างชัดเจน แต่ไม่ใช่ทั้งสองตัว - person Nick Strupat; 04.02.2015