Perversion. Does exist any way to natively use ref

2019-09-03 10:45发布

问题:

I have some variables which were given through ref keyword in my function. I want to use ref-variables in lambda expression without using local variables exactly.

I know that C# can't merge lambdas and ref-variables in work. But doesn't exist any perversion to make ref-variables work in lambda-expression?

Pseudo-code (wanna-be C#):

T MyFunction<T>(ref T x, ref T y)
{ 
    return (Func<T>) ( () => ( (100 * (x - y)) / x ) (); 
} 

I want it:

1). Be generic.

2). Accept as arguments the generic-types by references.

3). Using two options upper make it work with lambdas.

4). Return the result with using generic.

5). Be an organic-programming code :) Joke.

And call smth. like that:

int x = 21, y = 9;
int result = MyFunction<int>(ref x, ref y);

And with other types etc...

double x = 21.5, y = 9.3;
double result = MyFunction<double>(ref x, ref y);

Pity, that such constructions and desires C# couldn't give me, so I'm going to look at Lisp/Haskell ( maybe F# ).

(PS) => ("So I want to have a hard sex with C# possibilities exactly as you can see.")

回答1:

I'm posting a simple unsafe method, but you can say goodbye to generics. It's bad practice to use the code, but I guess that it answers the question, somewhat.

static unsafe int MyFunction(ref int value)
{
    fixed (int* temp = &value)
    {
        var pointer = temp;
        return new Func<int>(() => *pointer += 10)();
    }
}

Use it through:

var value = 42;
var returnedValue = MyFunction(ref value);
var success = value == returnedValue;
//success will be true

I repeat it again, I wouldn't suggest you to use it in any case, if you need a language designed for these things, there are many.