你能在C#中为一个变量赋一个函数吗?

Mou*_*Mou 13 c#

我看到一个函数可以在javascript中定义

var square = function(number) {return number * number};
Run Code Online (Sandbox Code Playgroud)

并且可以被称为

square(2);

var factorial = function fac(n) {return n<3 ? n : n*fac(n-1)};
print(factorial(3));
Run Code Online (Sandbox Code Playgroud)

c#代码

MyDelegate writeMessage = delegate ()
                              {
                                  Console.WriteLine("I'm called");
                              };
Run Code Online (Sandbox Code Playgroud)

所以我需要知道我可以在c#中以相同的方式定义一个函数.如果是,那么只需在c#中给出一小段上面的函数定义.谢谢.

sta*_*ica 19

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);
Run Code Online (Sandbox Code Playgroud)

任何这些更详细的形式也是可能的:(我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表达式"(=>).

PS: int对于诸如此类的方法可能不是合适的返回类型factorial.以上示例仅用于演示语法,因此请根据需要进行修改.


Nao*_*aor 18

您可以创建委托类型声明:

delegate int del(int number);
Run Code Online (Sandbox Code Playgroud)

然后分配并使用它:

   del square = delegate(int x)
    {
        return x * x;
    };

    int result= square (5);
Run Code Online (Sandbox Code Playgroud)

或者如上所述,您可以使用代理人的"快捷方式"(由代理人制作)并使用:

Func<[inputType], [outputType]> [methodName]= [inputValue]=>[returnValue]
Run Code Online (Sandbox Code Playgroud)

例如:

Func<int, int> square = x=>x*x;
int result=square(5);

您还有另外两个快捷方式:
没有参数的Func<int> p=()=>8;
Func :带有两个参数的Func:Func<int,int,int> p=(a,b)=>a+b;