2011-05-31 111 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); 
    } 
}