问题描述
我看到一个功能,可以在JavaScript中这样定义
i saw a function can be define in javascript like
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));
C#代码
c# code
MyDelegate writeMessage = delegate ()
{
Console.WriteLine("I'm called");
};
所以我需要知道我可以在C#中以同样的方式定义一个函数。如果是的话只是给上面像函数定义的一个小片段在c#请。谢谢
so i need to know that can i define a function in the same way in c#. if yes then just give a small snippet of above like function definition in c# please. thanks.
推荐答案
您可以创建委托类型声明:
You can create delegate type declaration:
delegate int del(int number);
,然后分配和使用它:
and then assign and use it:
del square = delegate(int x)
{
return x * x;
};
int result= square (5);
或者像说,你可以使用快捷方式来代表(从委托制造)和使用
Or as said, you can use a "shortcut" to delegates (it made from delegates) and use:
Func<[inputType], [outputType]> [methodName]= [inputValue]=>[returnValue]
例如:
Func键< INT,INT>方= X => X * X;
结果
INT结果=广场(5);
您还有其他两个快捷键:结果
Func键不带参数: Func键< INT> P =()=→8;
结果
Func键有两个参数: Func键< INT,INT,INT> P =(A,B)=> A + B
You also have two other shortcuts:
Func with no parameter: Func<int> p=()=>8;
Func with two parameters: Func<int,int,int> p=(a,b)=>a+b;
这篇关于分配的功能在C#中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!