Perversion. Does exist any way to natively use references with lambdas in C#?

风流意气都作罢 提交于 2019-12-11 16:29:36

问题


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.



来源:https://stackoverflow.com/questions/14185982/perversion-does-exist-any-way-to-natively-use-references-with-lambdas-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!