舍弃C#7.0中的功能重要性? [英] Discard feature significance in C# 7.0?

查看:93
本文介绍了舍弃C#7.0中的功能重要性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在经历新的 C#7.0 功能时,我坚持使用 discard 功能。它说:

While going through new C# 7.0 features, I stuck up with discard feature. It says:


丢弃是可以分配但不能从中读取
的局部变量。也就是说,它们是只写局部变量。

Discards are local variables which you can assign but cannot read from. i.e. they are "write-only" local variables.

,然后是一个示例:

if (bool.TryParse("TRUE", out bool _))

什么将是有益的实际用例?我的意思是,如果我将以常规方式定义它,说:

What is real use case when this will be beneficial? I mean what if I would have defined it in normal way, say:

if (bool.TryParse("TRUE", out bool isOK))


推荐答案

丢弃基本上是一种有意忽略与所生成的代码无关的局部变量的方法。就像当您调用返回值的方法时一样,但是,由于您只对它执行的基础操作感兴趣,因此不必将其输出分配给调用方方法中定义的局部变量,例如:

The discards are basically a way to intentionally ignore local variables which are irrelevant for the purposes of the code being produced. It's like when you call a method that returns a value but, since you are interested only in the underlying operations it performs, you don't assign its output to a local variable defined in the caller method, for example:

public static void Main(string[] args)
{
    // I want to modify the records but I'm not interested
    // in knowing how many of them have been modified.
    ModifyRecords();
}

public static Int32 ModifyRecords()
{
    Int32 affectedRecords = 0;

    for (Int32 i = 0; i < s_Records.Count; ++i)
    {
        Record r = s_Records[i];

        if (String.IsNullOrWhiteSpace(r.Name))
        {
            r.Name = "Default Name";
            ++affectedRecords;
        }
    }

    return affectedRecords;
}

实际上,我称其为装饰性功能……这是一个设计时功能(无论如何,都会执行有关丢弃变量的计算),这有助于使代码保持清晰,可读性和易于维护性。

Actually, I would call it a cosmetic feature... in the sense that it's a design time feature (the computations concerning the discarded variables are performed anyway) that helps keeping the code clear, readable and easy to maintain.

我找到了以下示例您提供的链接有点误导。如果我尝试将 String 解析为 Boolean ,则可能要在代码中的某个位置使用解析后的值。否则,我将尝试查看 String 是否对应于 Boolean 正则表达式,例如...如果正确处理了大小写,即使是简单的 if 语句也可以完成此工作)。我并不是说这永远不会发生,或者这是一种不好的做法,我只是说这不是您可能需要产生的最常见的编码模式。

I find the example shown in the link you provided kinda misleading. If I try to parse a String as a Boolean, chances are I want to use the parsed value somewhere in my code. Otherwise I would just try to see if the String corresponds to the text representation of a Boolean (a regular expression, for example... even a simple if statement could do the job if casing is properly handled). I'm far from saying that this never happens or that it's a bad practice, I'm just saying it's not the most common coding pattern you may need to produce.

相反,本文中提供的示例确实显示了完整的示例。此功能的潜力:

The example provided in this article, on the opposite, really shows the full potential of this feature:

public static void Main()
{
    var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);
    Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:N0}");
}

private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2)
{
    int population1 = 0, population2 = 0;
    double area = 0;

    if (name == "New York City")
    {
        area = 468.48;

        if (year1 == 1960) {
            population1 = 7781984;
        }

        if (year2 == 2010) {
            population2 = 8175133;
        }

        return (name, area, year1, population1, year2, population2);
    }

    return ("", 0, 0, 0, 0, 0);
}

从上面的代码中我可以看到, discards C#的最新版本中引入的其他范例(例如元组解构

From what I can see reading the above code, it seems that the discards have a higher sinergy with other paradigms introduced in the most recent versions of C# like tuples deconstruction.

对于 Matlab 程序员来说,丢弃远不是一个新概念,因为编程语言自非常非常非常长的时间(可能是从一开始就开始,但我不能肯定地说)。官方文档对它们的描述如下(链接此处):

For Matlab programmers, discards are far from being a new concept because the programming language implements them since very, very, very long time (probably since the beginning, but I can't say for sure). The official documentation describes them as follows (link here):


文件部分功能



helpFile = which('help');
[helpPath,name,ext] = fileparts('C:\Path\data.txt');




当前工作空间现在包含文件部分中的三个变量:helpPath,name,和分机。在这种情况下,变量很小。但是,某些函数返回使用更多内存的结果。如果不需要这些变量,则会浪费系统空间。

The current workspace now contains three variables from fileparts: helpPath, name, and ext. In this case, the variables are small. However, some functions return results that use much more memory. If you do not need those variables, they waste space on your system.

使用波浪号(〜)忽略第一个输出:

Ignore the first output using a tilde (~):



[~,name,ext] = fileparts(helpFile);

唯一的区别是,在 Matlab ,通常会跳过丢弃输出的内部计算,因为输出参数很灵活,您可以知道调用方请求了多少个参数,以及其中之一。

The only difference is that, in Matlab, inner computations for discarded outputs are normally skipped because output arguments are flexible and you can know how many and which one of them have been requested by the caller.

这篇关于舍弃C#7.0中的功能重要性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆