我最近一直在钻研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)
归档时间: |
|
查看次数: |
922 次 |
最近记录: |