【问题标题】:Can I declare a variable that is used in a line and discarded right after?我可以声明一个在一行中使用并在之后丢弃的变量吗?
【发布时间】:2021-06-02 03:35:29
【问题描述】:

假设我有这个代码:

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

我知道where 不存在。我尝试使用using var c = a + b,但我认为这是不可能的。有什么办法吗?

【问题讨论】:

    标签: c# variables


    【解决方案1】:

    你想做的事情让我想起了 Kotlin 的 scope functions,特别是 let。你可以为此编写一个扩展方法:

    static class ScopeFunctions
    {
        public static U Let<T, U>(this T x, Func<T, U> func) => func(x);
    }
    

    用法:

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

    x 成为要存储 (a+b) 的“'local' 变量,这样我就不需要计算两次”你“立即丢弃”,因为x 将超出范围之外lambda。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多