2009-04-12 12 views
10

सादगी के लिए, मान लीजिए कि मैं टाइप int के लिए एक एक्सटेंशन विधि लिखना चाहता हूं? और int:प्रकार और शून्य पर विस्तार विधि <type>

public static class IntExtentions 
{ 
    public static int AddOne(this int? number) 
    { 
     var dummy = 0; 
     if (number != null) 
      dummy = (int)number; 

     return dummy.AddOne(); 
    } 

    public static int AddOne(this int number) 
    { 
     return number + 1; 
    } 
} 

इस किया जा सकता है केवल 1 विधि का उपयोग कर?

उत्तर

16

दुर्भाग्य से नहीं। आप int बना सकते हैं? (या जो भी शून्य प्रकार आप उपयोग कर रहे हैं) विधि गैर-शून्य विधि को बहुत आसानी से कॉल करें, इसलिए आपको 2 विधियों के साथ किसी भी तर्क को डुप्लिकेट करने की आवश्यकता नहीं है - उदा।

public static class IntExtensions 
{ 
    public static int AddOne(this int? number) 
    { 
     return (number ?? 0).AddOne(); 
    } 

    public static int AddOne(this int number) 
    { 
     return number + 1; 
    } 
} 
+0

अच्छा एक! मेरे लिए काम किया – Jacques

8

नहीं आप नहीं कर सकते। यह निम्न कोड

public static class Example { 
    public static int Test(this int? source) { 
    return 42; 
    } 
    public void Main() { 
    int v1 = 42; 
    v1.Test(); // Does not compile 
    } 
} 

आप प्रत्येक प्रकार (नल और नल नहीं) अगर आप चाहते हैं यह दोनों प्रकार पर इस्तेमाल के लिए एक विस्तार विधि लिखने के लिए की आवश्यकता होगी संकलन द्वारा प्रयोगात्मक सत्यापित किया जा सकता।

संबंधित मुद्दे