C# 讓方法有多個回傳值的方式(含使用範例)

Tuple

使用 C# 7 出的 Tuple 可以很輕易的達成,這也是最好理解的一種方式:
    
public (int, int) GetValues()
{
    return (1, 2);
}
    

使用範例:
    
var (a, b) = GetValues();
Console.WriteLine($"a: {a}, b: {b}");
    

也可以修改原本存在的變數,簡直就是 JavaScript 的解構賦值
    
int a = 0;
int b = 0;
Console.WriteLine($"a: {a}, b: {b}"); // a: 0, b: 0

(a, b) = GetValues();
Console.WriteLine($"a: {a}, b: {b}"); // a: 1, b: 2
    

延伸閱讀: C# Tuple 介紹

使用 out 關鍵字

這是筆者最常使用的方式,也是最推薦的,因為通常要傳出的數量只會有一兩個而已。
方法示範:
    
bool TryGetValue(int inputValue, out int outputValue)
{
    outputValue = inputValue;
    if (inputValue == 0) return false;
    return true;
}
    

使用示範:
    
var tryGetValue = TryGetValue(1, out int b);
Console.WriteLine($"tryGetValue: {tryGetValue}, b: {b}");
// tryGetValue: True, b: 1
    

在日常開發中很常會看到這種方式,例如 string 轉 int:
    
string input = "1";
if (!int.TryParse(input, out int number))
{
    throw new ArgumentException("請輸入數字");
}

Console.WriteLine($"number: {number}");
// number: 1
    

自訂類別

假設要傳出的內容很多,最好是使用自訂類別,確保各個型別正確、並且有好閱讀的註解,還可以依照需要建立建構子和預設值方便使用。
    
public class Student
{
    /// <summary>
    /// 學號
    /// </summary>
    public int Id { get; set; }
    
    /// <summary>
    /// 姓名
    /// </summary>
    public string Name { get; set; }
    
    /// <summary>
    /// 班級
    /// </summary>
    public string Class { get; set; }
    
    /// <summary>
    /// 年齡
    /// </summary>
    public int Age { get; set; }
}
    

    
public Student GetStudent()
{
    return new Student()
    {
        Id = 1,
        Name = "小明",
        Class = "一年一班",
        Age = 18
    };
}
    

使用示範:
    
var student = GetStudent();
Console.WriteLine($"學號: {student.Id}, 姓名: {student.Name}, 班級: {student.Class}, 年齡: {student.Age}");
// 學號: 1, 姓名: 小明, 班級: 一年一班, 年齡: 18
    

留言