代码之家  ›  专栏  ›  技术社区  ›  ccalboni

在if语句条件中声明并赋值变量,在语句体中重用

c#
  •  0
  • ccalboni  · 技术社区  · 7 年前

    我真的说不出这个问题的题目。不管怎样,假设我有这样一句话:

    if(myObject.SomeMethod() != null)
    {
        DoSomethingWith(myObject.SomeMethod());
    }
    

    我想避免打两次电话给你 SomeMethod()

    if(myObject.SomeMethod() result != null)
    {
        DoSomethingWith(result);
    }
    

    语言中有什么东西能帮我解决这个问题吗?目前,我的选择是:

    var result = myObject.SomeMethod();
    if(result != null)
    {
        DoSomethingWith(result);
    }
    

    if(myObject.SomeMethod() result != null)

    1 回复  |  直到 7 年前
        1
  •  6
  •   Tim Schmelter    7 年前

    嗯,我建议使用一个变量,就像你在第三个代码中做的那样。然而。。。

    你可以用 pattern matching 如果不想使用变量:

    if(myObject.SomeMethod() is var result && result != null)
    {
        DoSomethingWith(result);
    }
    

    但请注意,这并不阻止访问变量 result . 你甚至可以在 if . 如果您需要一个新的作用域: { if... }