discards 基本上是一种有意忽略与生成代码的目的无关的局部变量的方法。这就像当您调用一个返回值的方法时,由于您只对它执行的底层操作感兴趣,因此您不会将其输出分配给调用者方法中定义的局部变量,例如:
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;
}
实际上,我将其称为外观功能...从某种意义上说,它是一种设计时功能(无论如何都会执行有关丢弃变量的计算),有助于保持代码清晰、可读和易于维护。
我发现您提供的链接中显示的示例有点误导。如果我尝试将String 解析为Boolean,我很可能想在代码中的某处使用解析后的值。否则,我将尝试查看String 是否对应于Boolean 的文本表示(例如regular expression......即使是简单的if 语句也可以完成这项工作,如果正确处理套管) .我并不是说这永远不会发生,或者说这是一种不好的做法,我只是说这不是您可能需要产生的最常见的编码模式。
相反,this article 中提供的示例真正展示了此功能的全部潜力:
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# 的最新版本中引入的其他范例相比具有更高的效能,例如tuples deconstruction。
对于Matlab 程序员来说,discards 远不是一个新概念,因为编程语言实现它们的时间非常非常长(可能从一开始,但我不能肯定地说)。官方文档描述如下(链接here):
从fileparts function 请求所有三个可能的输出:
helpFile = which('help');
[helpPath,name,ext] = fileparts('C:\Path\data.txt');
当前工作区现在包含来自文件部分的三个变量:helpPath、name 和 ext。在这种情况下,变量很小。但是,某些函数返回的结果会占用更多内存。如果您不需要这些变量,它们会浪费您的系统空间。
使用波浪号 (~) 忽略第一个输出:
[~,name,ext] = fileparts(helpFile);
唯一的区别是,在Matlab 中,丢弃输出的内部计算通常会被跳过,因为输出参数是灵活的,您可以知道调用者请求了多少以及其中一个。