C#中的扩展方法 - 这是正确的吗?

Mic*_*ael 12 .net c# windows

我最近一直在钻研C#,我想知道是否有人会介意检查我的写作,以确保它是准确的?

示例:使用Extension方法计算阶乘.

例如,如果你想扩展int类型,你可以创建一个类,例如 NumberFactorial创建一个方法,例如Static Void Main,调用eg int x = 3 然后打印出行(一旦从扩展方法返回)

创建一个包含关键字"this"的公共静态方法,例如,这将int x 执行逻辑,然后将参数反馈给初始方法进行输出.

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            Console.WriteLine(x.factorial());
            Console.ReadLine();
        }
    }
    public static class MyMathExtension
    {
        public static int factorial(this int x)
        {
            if (x <= 1) return 1;
            if (x == 2) return 2;
            else
                return x * factorial(x - 1);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ner 9

对,那是正确的.

扩展方法被定义为静态方法,但是通过使用实例方法语法来调用.它们的第一个参数指定方法操作的类型,参数前面有this修饰符.当您使用using指令将命名空间显式导入源代码时,扩展方法仅在范围内.

您可以在此处此处找到有关扩展方法的更多信息