在 c# 7 中可以为参数列表中的 out
变量声明变量:
if (int.TryParse(input, out int result))
WriteLine(result);
是否可以在参数列表中声明(“非输出”)变量?像这样:
if (!string.IsNullOrEmpty(string result=FuncGetStr()))
WriteLine(result);
最佳答案
你不能在参数列表中这样做,不。
您可以为此使用模式匹配,但我不建议这样做:
if (FuncGetStr() is string result && !string.IsNullOrEmpty(result))
这将声明保留在 if
的源代码中,但 result
的范围仍然是封闭 block ,所以我认为将其分开会更简单输出:
// Mostly equivalent, and easier to read
string result = FuncGetStr();
if (!string.IsNullOrEmpty(result))
{
...
}
我能想到两个区别:
result
未在第一个版本中的if
语句之后明确赋值
如果 string.IsNullOrEmpty
,因为is
模式不会匹配。因此,您可以将其写为:if (FuncGetStr() is string result && result != "")
FuncGetStr()
返回 null,则在第一个版本中甚至不会调用 更糟糕的是,您可以做到这一点,使用一个帮助器方法来让您使用out
参数。这是一个完整的例子。请注意,我不建议这样做。
// EVIL CODE: DO NOT USE
using System;
public class Test
{
static void Main(string[] args)
{
if (!string.IsNullOrEmpty(Call(FuncGetStr, out string result)))
{
Console.WriteLine(result);
}
}
static string FuncGetStr() => "foo";
static T Call<T>(Func<T> func, out T x) => x = func();
}
关于c# - 在参数列表中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48582030/