2009-08-14 14 views
59

संभव डुप्लिकेट int:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?सी # कोड संकलित नहीं होगा। बातिल और के बीच कोई अंतर्निहित रूपांतरण

क्यों नहीं इस काम करता है? वैध कोड की तरह लगता है।

string cert = ddCovCert.SelectedValue; 
    int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert); 
    Display(x); 

मुझे यह कैसे कोड करना चाहिए? विधि एक शून्य है। यदि ड्रॉप डाउन में एक स्ट्रिंग चयनित है तो मुझे इसे int में पार्स करने की आवश्यकता है अन्यथा मैं विधि को शून्य से गुजरना चाहता हूं।

+4

डुप्लिकेट (पूर्णांक?) - कृपया http://stackoverflow.com/questions/858080 देखना/nullable-type-and-the-ternary-operator-why-wont-this-work –

+1

इसके अलावा अधिक जानकारी के लिए, कृपया http://stackoverflow.com/questions/220250/in-c-why-cant-a- सशर्त-ऑपरेटर-implicitly-cast-to-a-nullable-type –

उत्तर

195
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert); 
+0

सुंदर। धन्यवाद! – Hcabnettek

+0

मुझे कभी-कभी इसकी आवश्यकता होती है, लेकिन हमेशा भूल जाते हैं और यहां समाप्त होते हैं: डी। धन्यवाद – Steven

+0

मेरा समय बचाया। धन्यवाद । –

7

मैं एक ही बात का सामना करना पड़ा ... मैं आम तौर पर सिर्फ अशक्त करने के लिए डाली

int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert); 
संबंधित मुद्दे