共用方式為


Discards - C# 基本概念

丟棄變數是刻意在應用程式代碼中不使用的佔位元變數。 捨棄相當於未指派的變數;它們沒有值。 捨棄會將意圖傳達給編譯程式和讀取程序代碼的其他人:您想要忽略表達式的結果。 您可能想要忽略表達式的結果、元組表達式的一個或多個成員、out 方法的參數,或模式匹配表達式的目標。

丟棄操作使您的程式碼意圖更加明確。 捨棄表示我們的程式代碼永遠不會使用 變數。 它們會增強其可讀性和可維護性。

您可以藉由將底線 (_) 指派為其名稱,以指出變數為捨棄。 例如,下列方法呼叫會傳回一個數組,其中第一個和第二個值作為捨棄值。 area 是一個先前宣告的變數,設定為GetCityInformation傳回的第三個元件。

(_, _, area) = city.GetCityInformation(cityName);

您可以使用捨棄來指定 Lambda 表達式的未使用輸入參數。 如需詳細資訊,請參閱 Lambda 運算式一文的 Lambda 運算式輸入參數一節。

_ 是有效的捨棄時,嘗試擷取其值或在指派作業中使用它會產生編譯程序錯誤 CS0103:「名稱 '_' 不存在於目前內容中」。 此錯誤是因為 _ 未指派值,甚至可能未指派儲存位置。 如果是實際的變數,就無法捨棄一個以上的值,如上一個範例所示。

Tuple 和物件解構

當您的應用程式代碼使用某些 tuple 元素但忽略其他元素時,捨棄符號在處理 tuple 時很有用。 例如,下列 QueryCityDataForYears 方法會傳回一個包含城市名稱、城市面積、某一年、該年份城市人口、另一年,以及該城市那一年的人口數的元組。 此範例會顯示這兩年之間的人口變化。 在元組可用的資料中,我們對城市區碼不感興趣,並在設計階段得知城市名稱及兩個日期。 因此,我們只對元組中所儲存的兩個人口值感興趣,而可以將其餘值視為 discard。

var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);

Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:N0}");

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);
}
// The example displays the following output:
//      Population change, 1960 to 2010: 393,149

如需有關使用捨棄解構元組的詳細資訊,請參閱 解構元組與其他類型

類別 Deconstruct 、結構或介面的 方法也可讓您從 物件擷取和解構特定數據集。 當您只想要使用解構後值的子集時,可以使用捨棄符來忽略其他不需要的值。 下列範例會將 物件解構成四個 Person 字串(名字和姓氏、城市和州),但會捨棄姓氏和州。

using System;

namespace Discards
{
    public class Person
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string State { get; set; }

        public Person(string fname, string mname, string lname,
                      string cityName, string stateName)
        {
            FirstName = fname;
            MiddleName = mname;
            LastName = lname;
            City = cityName;
            State = stateName;
        }

        // Return the first and last name.
        public void Deconstruct(out string fname, out string lname)
        {
            fname = FirstName;
            lname = LastName;
        }

        public void Deconstruct(out string fname, out string mname, out string lname)
        {
            fname = FirstName;
            mname = MiddleName;
            lname = LastName;
        }

        public void Deconstruct(out string fname, out string lname,
                                out string city, out string state)
        {
            fname = FirstName;
            lname = LastName;
            city = City;
            state = State;
        }
    }
    class Example
    {
        public static void Main()
        {
            var p = new Person("John", "Quincy", "Adams", "Boston", "MA");

            // Deconstruct the person object.
            var (fName, _, city, _) = p;
            Console.WriteLine($"Hello {fName} of {city}!");
            // The example displays the following output:
            //      Hello John of Boston!
        }
    }
}

如需解構具有捨棄之使用者定義型別的詳細資訊,請參閱 解構 Tuple 和其他類型

使用 switch 進行模式比對

捨棄模式可用於模式比對與 switch 運算式。 每個運算式,包括 null,一律符合捨棄模式。

下列範例會 ProvidesFormatInfo 定義方法,這個方法會使用 switch 表示式來判斷物件是否提供 IFormatProvider 實作,並測試物件是否為 null。 它也會使用捨棄模式來處理任何其他類型的非 Null 物件。

object?[] objects = [CultureInfo.CurrentCulture,
                   CultureInfo.CurrentCulture.DateTimeFormat,
                   CultureInfo.CurrentCulture.NumberFormat,
                   new ArgumentException(), null];
foreach (var obj in objects)
    ProvidesFormatInfo(obj);

static void ProvidesFormatInfo(object? obj) =>
    Console.WriteLine(obj switch
    {
        IFormatProvider fmt => $"{fmt.GetType()} object",
        null => "A null object reference: Its use could result in a NullReferenceException",
        _ => "Some object type without format information"
    });
// The example displays the following output:
//    System.Globalization.CultureInfo object
//    System.Globalization.DateTimeFormatInfo object
//    System.Globalization.NumberFormatInfo object
//    Some object type without format information
//    A null object reference: Its use could result in a NullReferenceException

呼叫具有 out 參數的方法

呼叫 Deconstruct 方法來解構使用者定義型別(類別、結構或介面的實例),您可以捨棄個別 out 自變數的值。 但是,您也可以在呼叫包含out參數的任何方法時,捨棄參數out的值。

下列範例會呼叫 DateTime.TryParse(String, out DateTime) 方法來判斷日期的字串表示是否在目前文化特性中有效。 因為範例只涉及驗證日期字串,而不是剖析以擷取日期, out 所以方法的自變數是捨棄。

string[] dateStrings = ["05/01/2018 14:57:32.8", "2018-05-01 14:57:32.8",
                      "2018-05-01T14:57:32.8375298-04:00", "5/01/2018",
                      "5/01/2018 14:57:32.80 -07:00",
                      "1 May 2018 2:57:32.8 PM", "16-05-2018 1:00:32 PM",
                      "Fri, 15 May 2018 20:10:57 GMT"];
foreach (string dateString in dateStrings)
{
    if (DateTime.TryParse(dateString, out _))
        Console.WriteLine($"'{dateString}': valid");
    else
        Console.WriteLine($"'{dateString}': invalid");
}
// The example displays output like the following:
//       '05/01/2018 14:57:32.8': valid
//       '2018-05-01 14:57:32.8': valid
//       '2018-05-01T14:57:32.8375298-04:00': valid
//       '5/01/2018': valid
//       '5/01/2018 14:57:32.80 -07:00': valid
//       '1 May 2018 2:57:32.8 PM': valid
//       '16-05-2018 1:00:32 PM': invalid
//       'Fri, 15 May 2018 20:10:57 GMT': invalid

獨立捨棄

您可以使用獨立捨棄來指出您選擇忽略的任何變數。 一個典型的用法是使用指派,以確保自變數不是 Null。 下列程式代碼會使用捨棄來強制指派。 指定的右側使用空合併運算子,當自變數為System.ArgumentNullException時擲回null。 程序代碼不需要指派的結果,因此會捨棄。 表達式會強制進行空值檢查。 丟棄表明您的意圖:指派任務的結果不需要也不會被使用。

public static void Method(string arg)
{
    _ = arg ?? throw new ArgumentNullException(paramName: nameof(arg), message: "arg can't be null");

    // Do work with arg.
}

下列範例會使用獨立捨棄來忽略 Task 異步作所傳回的物件。 指派任務的效果是抑制作業在完成時拋出的例外狀況。 它會讓您的意圖清楚:您想要捨棄 Task,並忽略從該異步操作中產生的任何錯誤。

private static async Task ExecuteAsyncMethods()
{
    Console.WriteLine("About to launch a task...");
    _ = Task.Run(() =>
    {
        var iterations = 0;
        for (int ctr = 0; ctr < int.MaxValue; ctr++)
            iterations++;
        Console.WriteLine("Completed looping operation...");
        throw new InvalidOperationException();
    });
    await Task.Delay(5000);
    Console.WriteLine("Exiting after 5 second delay");
}
// The example displays output like the following:
//       About to launch a task...
//       Completed looping operation...
//       Exiting after 5 second delay

如果未將任務指派給棄置,以下程式碼會產生編譯器警告:

private static async Task ExecuteAsyncMethods()
{
    Console.WriteLine("About to launch a task...");
    // CS4014: Because this call is not awaited, execution of the current method continues before the call is completed.
    // Consider applying the 'await' operator to the result of the call.
    Task.Run(() =>
    {
        var iterations = 0;
        for (int ctr = 0; ctr < int.MaxValue; ctr++)
            iterations++;
        Console.WriteLine("Completed looping operation...");
        throw new InvalidOperationException();
    });
    await Task.Delay(5000);
    Console.WriteLine("Exiting after 5 second delay");

備註

如果您使用調試程序執行上述兩個範例之一,調試程式會在擲回例外狀況時停止程式。 如果沒有附加調試程式,這兩種情況下都會以無訊息方式忽略例外狀況。

_ 也是有效的標識碼。 在支持的內容之外使用時, _ 不會被視為捨棄,而是視為有效的變數。 如果名為 _ 的識別符號已在範圍內,則使用 _ 作為單獨捨棄可能會導致:

  • 不小心將預定捨棄的值指派給範圍中的 _ 變數,從而修改了該變數的值。 例如:
    private static void ShowValue(int _)
    {
       byte[] arr = [0, 0, 1, 2];
       _ = BitConverter.ToInt32(arr, 0);
       Console.WriteLine(_);
    }
     // The example displays the following output:
     //       33619968
    
  • 違反類型安全性的編譯程序錯誤。 例如:
    private static bool RoundTrips(int _)
    {
       string value = _.ToString();
       int newValue = 0;
       _ = Int32.TryParse(value, out newValue);
       return _ == newValue;
    }
    // The example displays the following compiler error:
    //      error CS0029: Cannot implicitly convert type 'bool' to 'int'
    

另請參閱