2009-04-12 39 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; 
    } 
} 

這可以使用只有一種方法?

回答

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 2014-09-02 10:49:22

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

你需要編寫每種類型(可空和不可爲空值),如果你想它這兩種類型使用的擴展方法進行驗證。