Func / Action delegates with reference arguments/parameters or anonymous functions

后端 未结 2 783
甜味超标
甜味超标 2021-01-12 09:10

I just wondered, how the exact syntax is for ref and out parameters for delegates and inline lambda functions.

here is an example

i

相关标签:
2条回答
  • 2021-01-12 09:50

    You can't use Action, Func<T>, or the built-in delegates, but need to define your own in this case:

    delegate void ActionByRef<T>(ref T value);
    

    Then, given this, you can have:

    int value = 3;
    ActionByRef<int> f2 = DoSomething;
    f2(ref value);
    
    0 讨论(0)
  • 2021-01-12 09:51

    You need to define a new delegate type for this method signature:

    delegate void RefAction<in T>(ref T obj);
    
    public void F()
    {
        RefAction<int> f2 = DoSomething;
        int x = 0;
        f2(ref x);
    }
    

    The reason why the .NET Framework does not include this type is probably because ref parameters are not very common, and the number of needed types explodes if you add one delegate type for each possible combination.

    0 讨论(0)
提交回复
热议问题