2011-05-31 92 views
2

請有人可以給我提供一個簡單的擴展方法,例如對一個數字進行平方。C# - 擴展方法示例

我得出了這樣的僞代碼:

class Program 

int = x 
--------------------- 

public static int square (this int x) 

return x * square 
+1

您是否閱讀過文檔? – SLaks 2011-05-31 14:50:12

+0

我不在c#中編碼,並想知道是否有人可以幫助 – Dan 2011-05-31 14:51:21

+0

我通常會粘貼http://msdn.microsoft.com/en-us/library/bb383977.aspx,但指出它說:「請注意,它是在非嵌套的非泛型靜態類中定義「而不是」請注意,它必須在非嵌套的非泛型靜態類中定義**「 – blizpasta 2011-05-31 14:56:40

回答

4
public static class NumberExtensions 
{ 
    public static int Square(this int n) 
    { 
    return n*n; 
    } 
} 

現在,你可以說:

int number=5.Square(); 
+0

乾杯肖恩,所有的解決方案都很好 – Dan 2011-05-31 15:23:51

1
public static class SomeClass { 
    public static int Square(this int x) { 
     return x * x; 
    } 
} 
3

這裏是你將如何編寫方法:

public static class ExtnMethods 
{ 
    public static int Square(this int x) 
    { 
     return x * x; 
    } 
} 

需要注意上面的代碼中一些重要的事情:

  • 該類必須是靜態的和非抽象的
  • 參數this int x指定方法作用於int

你會使用它,像這樣:

Console.WriteLine(5.Square()); 
// prints 25 
+0

我編輯了你的答案,你忘了使Square方法靜態! ;) – 2011-05-31 14:55:16

+0

@Matias,謝謝! – jjnguy 2011-05-31 14:55:34

1

擴展方法:

static class MathExtensions { 

    public static Int32 Square(this Int32 x) { 
    return x*x; 
    } 

} 

如何使用它:

var x = 5; 
var xSquared = x.Square(); 
+0

我已經編輯了你的答案哈哈,jjnguy和你忘了讓Square方法靜態!啊,一些建議,不建議使用CLR類型名稱。 – 2011-05-31 14:57:04

-1

在這個例子中,我試圖向您展示如何在一個表達式中使用多個擴展方法。

class Program 
{ 
    static void Main(string[] args) 
    { 
     int x = 13; 
     var ans = x.Cube().Half().Square(); 
     Console.WriteLine(ans); 
    } 
} 

static class IntExtensions 
{ 
    public static int Half(this int source) 
    { 
     return source/2; 
    } 
    public static int Cube(this int source) 
    { 
     return (int)Math.Pow(source, 3); 
    } 
    public static int Square(this int source) 
    { 
     return (int)Math.Pow(source, 2); 
    } 
}