当前位置:网站首页>C anonymous function

C anonymous function

2022-06-09 06:01:00 Go_ Accepted

1、 Anonymous functions

Functions without names , It is mainly used in conjunction with delegation and events , Anonymous functions are not used without delegates and events

2、 Basic grammar

delegate ( parameter list ){
      // Functional logic 
};

When to use ?

(1) When passing delegate parameters in a function

(2) Delegate and event assignment

3、 Use

(1) No parameter no return

Action a = delegate () {
    Console.WriteLine(" Anonymous functions ");
};
a();

(2) Ginseng  

Action<int> a = delegate (int value) {
    Console.WriteLine(value);
};
a(100);

(3) There is a return value

direct return, Automatic recognition of return value

Func<string> a = delegate () {
    return " Return value anonymous function ";
};
Console.WriteLine(a());

(4) In general, it will be passed as a function parameter , Or as a function return value

class Test {
    public Action action;

    //  Pass as a parameter 
    public void DoSomeThing(int a, Action action) {
        Console.WriteLine(a);
        action();
    }

    //  As return value  
    public Action GetFun() {
        return TestRet;
    }

    public void TestRet() {

    }

    //  Or in one step 
    public Action GetFun2() {
        return delegate () {
            Console.WriteLine(" Anonymous function as return value ");
        };
    }
}

A call passed as a parameter

Test t = new Test();
//  Mode one 
t.DoSomeThing(100, delegate () {
    Console.WriteLine(" Anonymous functions passed as arguments ");
});

//  Mode two 
Action ac = delegate () {
    Console.WriteLine(" Anonymous functions passed as arguments ");
};
t.DoSomeThing(100, ac);

Call as return value

//  Mode one 
Action ac = t.GetFun2();
ac();
//  Mode two 
t.GetFun2()();

4、 Disadvantages of anonymous functions

After adding to the delegate or event container , Cannot be removed separately , Can only be emptied directly

  Be careful !!! Anonymous functions change the life cycle of variables , for example :

static Func<int, int> TestFun(int v) {
    return delegate (int i) {
        return i * v;
    };
}

And then call

Func<int, int> fun = TestFun(2);
Console.WriteLine(fun(3))

You can find ,v The life cycle of TestFun() It doesn't stop at the end

原网站

版权声明
本文为[Go_ Accepted]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090559147514.html