1. 程式人生 > >C# 好程式碼學習筆記(1):檔案操作、讀取檔案、Debug/Trace 類、Conditional條件編譯、CLS

C# 好程式碼學習筆記(1):檔案操作、讀取檔案、Debug/Trace 類、Conditional條件編譯、CLS

[TOC] 目錄: 1,檔案操作 2,Debug、Trace類 3,條件編譯 4,MethodImpl 特性 5,CLSComplianAttribute 6,必要時自定義類型別名 最近在閱讀 .NET Core Runtime 的原始碼,參考大佬的程式碼,學習編寫技巧和提高程式碼水平。學習過程中將學習心得和值得應用到專案中的程式碼片段記錄下來,供日後查閱。 ### 1,檔案操作 這段程式碼在 `System.Private.CoreLib` 下,對 System.IO.File 中的程式碼進行精簡,供 CLR 使用。 當使用檔案時,要提前判斷檔案路徑是否存在,日常專案中要使用到檔案的地方應該不少,可以統一一個判斷檔案是否存在的方法: ```csharp public static bool Exists(string? path) { try { // 可以將 string? 改成 string if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPath(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[^1])) { return false; } return InternalExists(path); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } ``` 建議專案中對路徑進行最終處理的時候,都轉換為絕對路徑: ```csharp Path.GetFullPath(path) ``` 當然,相對路徑會被 .NET 正確識別,但是對於運維排查問題和各方面考慮,絕對路徑容易定位具體位置和排錯。 在編寫程式碼時,使用相對路徑,不要寫死,提高靈活性;在執行階段將其轉為絕對路徑; 上面的 `NotSupportedException` 等異常是操作檔案中可能出現的各種異常情況,對於跨平臺應用來說,這些異常可能都是很常見的,提前將其異常型別識別處理,可以優化檔案處理邏輯以及便於篩查處理錯誤。 ### 2,讀取檔案 這段程式碼在 System.Private.CoreLib 中。 有個讀取檔案轉換為 byte[] 的方法如下: ```csharp public static byte[] ReadAllBytes(string path) { // bufferSize == 1 used to avoid unnecessary buffer in FileStream using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1)) { long fileLength = fs.Length; if (fileLength > int.MaxValue) throw new IOException(SR.IO_FileTooLong2GB); int index = 0; int count = (int)fileLength; byte[] bytes = new byte[count]; while (count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) throw Error.GetEndOfFile(); index += n; count -= n; } return bytes; } } ``` 可以看到 FileStream 的使用,如果單純是讀取檔案內容,可以參考裡面的程式碼: ```csharp FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1) ``` 上面的程式碼同樣也存在 `File.ReadAllBytes` 與之對應, File.ReadAllBytes 內部是使用 `InternalReadAllBytes` 來處理文件讀取: ```csharp private static byte[] InternalReadAllBytes(String path, bool checkHost) { byte[] bytes; // 此 FileStream 的建構函式不是 public ,開發者不能使用 using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) { // Do a blocking read int index = 0; long fileLength = fs.Length; if (fileLength > Int32.MaxValue) throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB")); int count = (int) fileLength; bytes = new byte[count]; while(count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) __Error.EndOfFile(); index += n; count -= n; } } return bytes; } ``` 這段說明我們可以放心使用 `File` 靜態類中的函式,因為裡面已經處理好一些邏輯了,並且自動釋放檔案。 如果我們手動 `new FileStream` ,則要判斷一些情況,以免使用時報錯,最好參考一下上面的程式碼。 .NET 檔案流快取大小預設是 `4096` 位元組: ```csharp internal const int DefaultBufferSize = 4096; ``` 這段程式碼在 File 類中定義,開發者不能設定快取塊的大小,大多數情況下,4k 是最優的塊大小。 ReadAllBytes 的檔案大小上限是 2 GB。 ### 3,Debug 、Trace類 這兩個類的名稱空間為 `System.Diagnostics`,Debug 、Trace 提供一組有助於除錯程式碼的方法和屬性。 Debug 中的所有函式都不會在 Release 中有效,並且所有輸出流不會在控制檯顯示,**必須註冊偵聽器才能讀取這些流**。 Debug 可以列印除錯資訊並使用斷言檢查邏輯,使程式碼更可靠,而**不會影響發運產品的效能和程式碼大小**。 這類輸出方法有 Write 、WriteLine 、 WriteIf 和 WriteLineIf 等,這**裡輸出不會直接列印到控制檯**。 如需將除錯資訊列印到控制檯,可以註冊偵聽器: ```csharp ConsoleTraceListener console = new ConsoleTraceListener(); Trace.Listeners.Add(console); ``` 注意, .NET Core 2.x 以上 Debug 沒有 Listeners ,因為 Debug 使用的是 Trace 的偵聽器。 我們可以給 Trace.Listeners 註冊偵聽器,這樣相對於 `Debug` 等效設定偵聽器。 ```csharp Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Debug.WriteLine("aa"); ``` .NET Core 中的監聽器都繼承了 TraceListener,如 TextWriterTraceListener、ConsoleTraceListener、DefaultTraceListener。 如果需要輸出到檔案中,可以自行繼承 `TextWriterTraceListener` ,編寫檔案流輸出,也可以使用 DelimitedListTraceListener。 示例: ```csharp TraceListener listener = new DelimitedListTraceListener(@"C:\debugfile.txt"); // Add listener. Debug.Listeners.Add(listener); // Write and flush. Debug.WriteLine("Welcome"); ``` 處理上述方法輸出控制檯,也可以使用 ```csharp ConsoleTraceListener console=... ...Listeners.Add(console); // 等效於 var console = new TextWriterTraceListener(Console.Out) ``` 為了格式化輸出流,可以使用 一下屬性控制排版: | 屬性 | 說明 | | ----------- | ------------------------------------------------------------ | | AutoFlush | 獲取或設定一個值,通過該值指示每次寫入後是否應在 Flush() 上呼叫 Listeners。 | | IndentLevel | 獲取或設定縮排級別。 | | IndentSize | 獲取或設定縮排的空格數。 | ```csharp // 1. Debug.WriteLine("One"); // Indent and then unindent after writing. Debug.Indent(); Debug.WriteLine("Two"); Debug.WriteLine("Three"); Debug.Unindent(); // End. Debug.WriteLine("Four"); // Sleep. System.Threading.Thread.Sleep(10000); ``` ``` One Two Three Four ``` `.Assert()` 方法對我們除錯程式很有幫助,Assert 向開發人員傳送一個強訊息。在 IDE 中,斷言會中斷程式的正常操作,但不會終止應用程式。 `.Assert()` 的最直觀效果是輸出程式的斷言位置。 ```csharp Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); int value = -1; // A. // If value is ever -1, then a dialog will be shown. Debug.Assert(value != -1, "Value must never be -1."); // B. // If you want to only write a line, use WriteLineIf. Debug.WriteLineIf(value == -1, "Value is -1."); ``` ``` ---- DEBUG ASSERTION FAILED ---- ---- Assert Short Message ---- Value must never be -1. ---- Assert Long Message ---- at Program.Main(String[] args) in ...Program.cs:line 12 Value is -1. ``` `Debug.Prinf()` 也可以輸出資訊,它跟 C 語言的 printf 函式行為一致,將後跟行結束符的訊息寫入,預設行終止符為回車符後跟一個換行符。 在 IDE 中執行程式時,使用 `Debug.Assert()`、`Trace.Assert()` 等方法 ,條件為 false 時,IDE 會斷言,這相當於條件斷點。 在非 IDE 環境下,程式會輸出一些資訊,但不會有中斷效果。 ```csharp Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.Assert(false); ``` ``` Process terminated. Assertion Failed at Program.Main(String[] args) in C:\ConsoleApp4\Program.cs:line 44 ``` 個人認為,可以將 Debug、Trace 引入專案中,與日誌元件配合使用。Debug、Trace 用於記錄程式執行的診斷資訊,便於日後排查程式問題;日誌用於記錄業務過程,資料資訊等。 `.Assert()` 的原理, 在 true 時什麼都不做;在 false 時呼叫 Fail 函式;如果你不註冊偵聽器的話,預設也沒事可做。 `.Assert()` 唯一可做的事情是等條件為 false 時,執行 Fail 方法,當然我們也可以手動直接呼叫 Fail 方法,Fail 的程式碼如下: ```csharp public static void Fail(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Fail(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Fail(message); if (AutoFlush) listener.Flush(); } } else { listener.Fail(message); if (AutoFlush) listener.Flush(); } } } } ``` ### 4,條件編譯 `#if` 條件編譯會隱藏非條件(#else if)程式碼,我們開發中很可能會忽略掉這部分程式碼,當我們切換條件常量到這部分程式碼時,很可能因為各種原因導致報錯。 如果使用特性進行條件編譯標記,在開發過程中就可以留意到這部分程式碼。 ``` [Conditional("DEBUG")] ``` 例如,當使用修改所有引用-修改一個類成員變數或者靜態變數名稱時,`#if` 非條件中的程式碼不會被修改,因為這部分程式碼“無效”,而且使用 `[Conditional("DEBUG")]` 的程式碼則跟條件無關,會被同步修改。 `Conditional` 特性標記的方法等,在開發過程中保持有效,當在編譯時可能被排除。 程式碼片段只能使用 `#if` 了,如果是單個方法,則可以使用 `Conditional` 。 ### 5,MethodImpl 特性 此特性在 System.Runtime.CompilerServices 名稱空間中,指定如何實現方法的詳細資訊。 行內函數使用方法可參考 https://www.whuanle.cn/archives/995 MethodImpl 特性可以影響 JIT 編譯器的行為。 無法使用 `MemberInfo.GetCustomAttributes` 來獲取此特性的資訊,即不能通過獲取特性的方法獲取跟 `MethodImpl` 有關的資訊(反射),只能呼叫 `MethodInfo.GetMethodImplementationFlags()` 或 `ConstructorInfo.GetMethodImplementationFlags ()` 來檢索。 MethodImpl 可以在方法以及建構函式上使用。 MethodImplOptions 用於設定編譯行為,列舉值可組合使用,其列舉說明如下: | 列舉 | 列舉值 | 說明 | | ---------------------- | ------ | ------------------------------------------------------------ | | AggressiveInlining | 256 | 如可能應將該方法進行內聯。 | | AggressiveOptimization | 512 | 此方法包含一個熱路徑,且應進行優化。 | | ForwardRef | 16 | 已宣告該方法,但在其他位置提供實現。 | | InternalCall | 4096 | 該呼叫為內部呼叫,也就是說它呼叫了在公共語言執行時中實現的方法。 | | NoInlining | 8 | 該方法不能為內聯方法。 內聯是一種優化方式,通過該方式將方法呼叫替換為方法體。 | | NoOptimization | 64 | 除錯可能的程式碼生成問題時,該方法不由實時 (JIT) 編譯器或本機程式碼生成優化(請參閱 [Ngen.exe](https://docs.microsoft.com/zh-cn/dotnet/framework/tools/ngen-exe-native-image-generator))。 | | PreserveSig | 128 | 完全按照宣告匯出方法簽名。 | | Synchronized | 32 | 該方法一次性只能在一個執行緒上執行。 靜態方法在型別上鎖定,而例項方法在例項上鎖定。 只有一個執行緒可在任意例項函式中執行,且只有一個執行緒可在任意類的靜態函式中執行。 | | Unmanaged | 4 | 此方法在非託管的程式碼中實現。 | `Synchronized` 修飾的方法可以避免多執行緒中的一些問題,但是不建議對公共型別使用鎖定例項或型別上的鎖定,因為 `Synchronized` 可以對非自己的程式碼的公共型別和例項進行鎖定。 這可能會導致死鎖或其他同步問題。 意思是說,如果共享的成員已經設定了鎖,那麼不應該再在 `Synchronized` 方法中使用,這樣雙重鎖定容易導致死鎖以及其他問題。 ### 5,CLSCompliantAttribute 指示程式元素是否符合公共語言規範 (CLS)。 CLS規範可參考: https://docs.microsoft.com/en-us/dotnet/standard/language-independence https://www.ecma-international.org/publications/standards/Ecma-335.htm 全域性開啟方法: 程式目錄下新增一個 AssemblyAttribytes.cs 檔案,或者開啟 obj 目錄,找到 AssemblyAttributes.cs 結尾的檔案,如 .NETCoreApp,Version=v3.1.AssemblyAttributes.cs,新增: ``` using System; // 這行已經有的話不要加 [assembly: CLSCompliant(true)] ``` 之後就可以在程式碼中使用 `[CLSCompliant(true)]` 特性。 區域性開啟: 也可以放在類等成員上使用: ``` [assembly: CLSCompliant(true)] ``` 您可以將特性應用於 CLSCompliantAttribute 下列程式元素:程式集、模組、類、結構、列舉、建構函式、方法、屬性、欄位、事件、介面、委託、引數和返回值。 但是,CLS 遵從性的概念**僅適用於程式集、模組、型別和型別的成員**。 程式編譯時預設不會檢查程式碼是否符合 CLS 要求,但是如果你的可以是公開的(程式碼共享、Nuget 釋出等),則建議使用使用 `[assembly: CLSCompliant(true)]` ,指明你的庫符合 CLS 要求。 在團隊開發中以及內部共享程式碼時,高質量的程式碼尤為重要,所以有必要使用工具檢查程式碼,如 roslyn 靜態分析、sonar 掃描等,也可以使用上面的特性,自動使用 CLS 檢查。 CLS 部分要求: 1. 無符號型別不應成為該類的公共介面的一部分(私有成員可以使用),例如 UInt32 這些屬於 C# 的型別,但不是 CLS “標準” 中的。 2. 指標等不安全型別不能與公共成員一起使用,就是公有方法中都不應該使用 unsafe 程式碼。(私有成員可以使用)。 3. 類名和成員名不應重名。雖然 C# 中區分大小寫,但是 CLS 不建議同名非過載函式,例如 MYTEST 跟 Mytest。 4. 只能過載屬性和方法,不應過載運算子。過載運算子容易導致呼叫者不知情時出現程式錯誤,並且過載運算子要排查問題十分困難。 我們可以編譯以下程式碼,嘗試使用 `CLSCompliant` : ```csharp [assembly: CLSCompliant(true)] [CLSCompliant(true)] public class Test { public void MyMethod() { } public void MYMETHOD() { } } ``` IDE 中會警告:warning CS3005: 僅大小寫不同的識別符號“Test.MYMETHOD()”不符合 CLS,編譯時也會提示 Warn。當然,不會阻止編譯,也不會影響程式執行。 總之,如果要標記一個程式集 CLS 規範,可以使用 `[assembly: CLSCompliant(true)]` 特性。 `[CLSCompliant(true)]` 特性指示這個元素符合 CLS 規範,這時編譯器或者 IDE 會檢查你的程式碼,檢查是否真的符合規範。 如果偏偏要寫不符合規範的程式碼,則可以使用 ` [CLSCompliant(false)]`。 ### 6,必要時自定義類型別名 C# 也可以定義類型別名。 ```csharp using intbyte = System.Int32; using intkb = System.Int32; using intmb = System.Int32; using intgb = System.Int32; using inttb = System.Int32; ``` ```csharp byte[] fileByte = File.ReadAllBytes("./666.txt"); intmb size = fileByte.Length / 1024; ``` 一些情況下,使用別名可以提高程式碼可讀性。真實專案不要使用以上程式碼,我只是寫個示例,這並不是合適的應用場景。 今天學習 Runtime 的程式碼就到這裡為止。