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])
);