我看到一个函数可以在javascript中定义,如
var square = function(number) {return number * number};
可以像
一样调用square(2);
var factorial = function fac(n) {return n<3 ? n : n*fac(n-1)};
print(factorial(3));
MyDelegate writeMessage = delegate ()
{
Console.WriteLine("I'm called");
};
所以我需要知道我可以在c#中以相同的方式定义一个函数。如果是,那么只需在c#中给出一小段上面的函数定义。感谢。
答案 0 :(得分:17)
Func<double,double> square = x => x * x;
// for recursion, the variable must be fully
// assigned before it can be used, therefore
// the dummy null assignment is needed:
Func<int,int> factorial = null;
factorial = n => n < 3 ? n : n * factorial(n-1);
以下任何更详细的表格都是可能的:(我使用square
作为例子):
Func<double,double> square = x => { return x * x; };
表达式扩展为语句块。
Func<double,double> square = (double x) => { return x * x; };
显式参数列表,而不仅仅是一个具有推断类型的参数。
Func<double,double> square = delegate(double x) { return x * x; };
这个使用较旧的“匿名委托”语法而不是所谓的“lambda表达式”(=>
)。
P.S。: int
可能不是factorial
等方法的合适返回类型。以上示例仅用于演示语法,因此请根据需要进行修改。
答案 1 :(得分:13)
您可以创建委托类型声明:
delegate int del(int number);
然后分配并使用它:
del square = delegate(int x)
{
return x * x;
};
int result= square (5);
或者如上所述,您可以使用代理人的“快捷方式”(由代表制作)并使用:
Func<[inputType], [outputType]> [methodName]= [inputValue]=>[returnValue]
例如:
Func<int, int> square = x=>x*x;
int result=square(5);
您还有两个其他快捷方式:
没有参数的Func:Func<int> p=()=>8;
Func有两个参数:Func<int,int,int> p=(a,b)=>a+b;