Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以声明一个在一行中使用并在之后立即丢弃的变量吗?_C#_Variables - Fatal编程技术网

C# 我可以声明一个在一行中使用并在之后立即丢弃的变量吗?

C# 我可以声明一个在一行中使用并在之后立即丢弃的变量吗?,c#,variables,C#,Variables,假设我有以下代码: int a = 1; int b = 2; string s = (a + b == 3 ? "3" : array[a + b]); 我想声明一个“局部”变量来存储(a+b),这样我就不需要计算两次。我想是这样的: int a = 1; int b = 2; string s = (c == 3 ? "3" : array[c]) where c = a + b; //from now on, c doesn't exist any

假设我有以下代码:

int a = 1;
int b = 2;
string s = (a + b == 3 ? "3" : array[a + b]);
我想声明一个“局部”变量来存储(a+b),这样我就不需要计算两次。我想是这样的:

int a = 1;
int b = 2;
string s = (c == 3 ? "3" : array[c]) where c = a + b;
//from now on, c doesn't exist anymore

我知道那里根本不存在
。我试着用var c=a+b使用
,但我认为这是不可能的。有办法吗?

你想做的事让我想起了科特林,特别是
let
。您可以为此编写扩展方法:

static class ScopeFunctions
{
    public static U Let<T, U>(this T x, Func<T, U> func) => func(x);
}
x
将成为“本地”变量来存储(a+b),这样我就不需要计算它两次”,然后您“立即放弃”,因为
x
将超出lambda之外的范围

string s = (a + b).Let(x => 
    (x == 3 ? "3" : array[x])
);