需要C#扩展方法示例

时间:2014-07-04 16:58:52

标签: c#

请提供给我并在C#中解释我的扩展方法。

像:

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

1 个答案:

答案 0 :(得分:1)

使用以下代码:

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

完整的演示代码

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