請有人可以給我提供一個簡單的擴展方法,例如對一個數字進行平方。C# - 擴展方法示例
我得出了這樣的僞代碼:
class Program
int = x
---------------------
public static int square (this int x)
return x * square
請有人可以給我提供一個簡單的擴展方法,例如對一個數字進行平方。C# - 擴展方法示例
我得出了這樣的僞代碼:
class Program
int = x
---------------------
public static int square (this int x)
return x * square
public static class NumberExtensions
{
public static int Square(this int n)
{
return n*n;
}
}
現在,你可以說:
int number=5.Square();
乾杯肖恩,所有的解決方案都很好 – Dan 2011-05-31 15:23:51
public static class SomeClass {
public static int Square(this int x) {
return x * x;
}
}
這裏是你將如何編寫方法:
public static class ExtnMethods
{
public static int Square(this int x)
{
return x * x;
}
}
需要注意上面的代碼中一些重要的事情:
this int x
指定方法作用於int
你會使用它,像這樣:
Console.WriteLine(5.Square());
// prints 25
我編輯了你的答案,你忘了使Square方法靜態! ;) – 2011-05-31 14:55:16
@Matias,謝謝! – jjnguy 2011-05-31 14:55:34
擴展方法:
static class MathExtensions {
public static Int32 Square(this Int32 x) {
return x*x;
}
}
如何使用它:
var x = 5;
var xSquared = x.Square();
我已經編輯了你的答案哈哈,jjnguy和你忘了讓Square方法靜態!啊,一些建議,不建議使用CLR類型名稱。 – 2011-05-31 14:57:04
在這個例子中,我試圖向您展示如何在一個表達式中使用多個擴展方法。
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);
}
}
您是否閱讀過文檔? – SLaks 2011-05-31 14:50:12
我不在c#中編碼,並想知道是否有人可以幫助 – Dan 2011-05-31 14:51:21
我通常會粘貼http://msdn.microsoft.com/en-us/library/bb383977.aspx,但指出它說:「請注意,它是在非嵌套的非泛型靜態類中定義「而不是」請注意,它必須在非嵌套的非泛型靜態類中定義**「 – blizpasta 2011-05-31 14:56:40