变态。在C#中是否存在任何使用lambdas参考的方式? [英] Perversion. Does exist any way to natively use references with lambdas in C#?

查看:160
本文介绍了变态。在C#中是否存在任何使用lambdas参考的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些变量通过我的函数中的 ref 关键字给出。我想在lambda表达式中使用ref-variables,而不使用局部变量。

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.

我知道C#不能合并lambdas和ref-variables。但是在lambda表达式中不存在任何使ref变量工作的谬误?

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?

伪代码(想要的C#)

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

我想要:

1)。通用。

2)。接受作为参数的通用类型。

3)。使用两个选项上方可以使用lambdas。

4)。返回结果使用泛型。

5)。是一个有机编程代码:)笑话。

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

并调用smth。像这样:

And call smth. like that:

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

与其他类型等...

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

可惜,这样的构造和欲望C#不能给我,所以我要去看在Lisp / Haskell(也许F#)。

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

(PS)=>(所以我想和C#的可能性完全一样,你可以看到。

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

推荐答案

我发布一个简单的不安全的方法,但你可以告别仿制药。

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)();
}
}

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

使用它:

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.

这篇关于变态。在C#中是否存在任何使用lambdas参考的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆