C#_元組Tuple使用技巧_我的函數一次想要回傳多個變數那就使用Tuple吧

 
在做一些需求以往可能拆分成獨立function做資料回傳
但也可能有時候要回傳不只一個內容甚至形態要不同的(不能用List或陣列)

比如一段function處理結果到底成功與否
可能以往回傳只會設計成true/false的boolean值型態
但當被要求要得知 false的exception error時候

就面臨到一個function一次要返回bool跟string的問題
這時Tuple就是一個我們很好拿來利用的語法

元組為C#7.0之後的產物
Nuget package 還需要額外安裝System.ValueTuple
並在
才能夠使用


以解壓縮功能為例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyApp.Function.DeZip
{
    public class ZipHelper
    {




        public static Tuple<bool,string> UnZip(string FileToUpZip, string UnZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return Tuple.Create(false,"解壓路徑不存在");
            }
            if (!Directory.Exists(UnZipedFolder))
            {
                Directory.CreateDirectory(UnZipedFolder);
            }
            ZipInputStream s = null;
            ZipEntry theEntry = null;
            string fileName;
            FileStream streamWriter = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(UnZipedFolder, theEntry.Name);
                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        streamWriter = File.Create(fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                return Tuple.Create(false, ex.Message);
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return Tuple.Create(true, "解壓成功");
        }
    }
}

任何回傳我都使用Tuple.Create一次將兩種不同型別的資料做return


而在外部使用接收資訊時
則是透過.Item1 , .Item2來接收




當然有人認為這種方式不太好命名item1 , item2 很容易不知道到底在回傳捨麼

因此到了更新一版的C# 允許我們自己去定義名稱不再用item1 , item2 ,...
用小括號包覆逗號分隔(跟python的tuple類似)





Ref:
C# Tuple快速上手
https://www.uuu.com.tw/Public/content/article/21/20210802.htm

C# Tuple 型別(types)
https://medium.com/@WilliamWhetstone/c-tuple-%E5%9E%8B%E5%88%A5-types-fe1127469981

[筆記] C# Tuple與ValueTuple的差異
https://dotblogs.com.tw/noncoder/2019/09/28/tuple-new-old















留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題