C#-扩展方法示例

本文关键字:方法 扩展 C#- | 更新日期: 2023-09-27 17:58:08

请有人给我提供一个简单的扩展方法,例如对一个数字进行平方。

我已经拟定了这样的伪代码:

class Program
int = x
---------------------
public static int square (this int x)
return x * square

C#-扩展方法示例

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

现在你可以说:

int number=5.Square();

以下是如何编写方法:

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

关于上述代码需要注意的一些重要事项:

  • 类必须是静态的和非抽象的
  • 参数this int x指定该方法作用于int

你会这样使用它:

Console.WriteLine(5.Square());
// prints 25
public static class SomeClass { 
   public static int Square(this int x) {
      return x * x;
   }
}

扩展方法:

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

如何使用:

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

在这个例子中,我试图向您展示如何在单个表达式中使用多个Extension方法。

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