How to declare a new delegate that is different from the function signature?

delegate void EmptyBody(ref int first );
delegate void AnotherEmptyBody(int first );
delegate void AnotherEmptyBody1(int first, int second);

public void aaa(params object[] pars)
{
    DoSpecifiedProcessing();

    pars[0] = 11;
}

public bool OnInIt()
{
    int b = 0;

    b = 44;
    var n = new EmptyBody(aaa);
    n(ref b);
    //b variable must be 11


    b = 44;
    var x = new AnotherEmptyBody(aaa);
    x(b);
    //b shoudn't be changed in this call, so it should be 44
}

I am trying to create a generic function such as aaathat defined in the code.
The first call should change bbecause it is passed as by-ref, but the second call should not change bbecause it is passed as by-val.

+4
source share
1 answer

You cannot do this with delegates, because the delegate settings aaado not match.
Instead, you can do something like this (create method adapters aaaRefIntand aaaInt):

public void aaaRefInt(ref int first)
{
    object[] Args = new object[]{first};        
    aaa(Args);
    first = (int)Args[0];
}

public void aaaInt(int first)
{
    aaa(new object[]{first});
}

var n = new EmptyBody(aaaRefInt);
n(ref b);

var x = new AnotherEmptyBody(aaaInt);
x(b);
0
source

Source: https://habr.com/ru/post/1530736/


All Articles