c# - 在参数列表中声明变量

标签 c# declare

在 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 语句之后明确赋值
  • 如果 FuncGetStr() 返回 null,则在第一个版本中甚至不会调用
  • string.IsNullOrEmpty,因为 is 模式不会匹配。因此,您可以将其写为:

    if (FuncGetStr() is string result && result != "")
    

更糟糕的是,您可以做到这一点,使用一个帮助器方法来让您使用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/

相关文章:

c# - 如何从解决方案中获取 64 位 exe 文件?

PHP声明编码

C 定义和 char 指针声明之间的错误

plsql - 如果 DECLARE 在 PL/SQL 存储过程中是可选的,为什么还要存在?

vba - 如何使用 VBA 在 Mac OS X 上读取/写入内存?

objective-c - 在 Objective-C 中转发声明一个结构

c# - 错误 : The object cannot be deleted because it was not found in the ObjectStateManager

c# - 如何使用 AutoMapper 处理 "inflate"实体

c# - MVC 中的 UrlParameter 始终为 null

c# - Owin SelfHost WebApi - 客户端在响应期间关闭连接会引发异常吗?