|
目錄: 1,文件操作 2,Debug、Trace類 3,條件編譯 4,MethodImpl 特性 5,CLSComplianAttribute 6,必要時自定義類型別名 最近在閱讀 .NET Core Runtime 的源碼,參考大佬的代碼,學(xué)習(xí)編寫技巧和提高代碼水平。學(xué)習(xí)過程中將學(xué)習(xí)心得和值得應(yīng)用到項(xiàng)目中的代碼片段記錄下來,供日后查閱。 1,文件操作這段代碼在 當(dāng)使用文件時,要提前判斷文件路徑是否存在,日常項(xiàng)目中要使用到文件的地方應(yīng)該不少,可以統(tǒng)一一個判斷文件是否存在的方法: 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;
}建議項(xiàng)目中對路徑進(jìn)行最終處理的時候,都轉(zhuǎn)換為絕對路徑: Path.GetFullPath(path) 當(dāng)然,相對路徑會被 .NET 正確識別,但是對于運(yùn)維排查問題和各方面考慮,絕對路徑容易定位具體位置和排錯。 在編寫代碼時,使用相對路徑,不要寫死,提高靈活性;在運(yùn)行階段將其轉(zhuǎn)為絕對路徑; 上面的 2,讀取文件這段代碼在 System.Private.CoreLib 中。 有個讀取文件轉(zhuǎn)換為 byte[] 的方法如下: 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 的使用,如果單純是讀取文件內(nèi)容,可以參考里面的代碼: FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1) 上面的代碼同樣也存在 private static byte[] InternalReadAllBytes(String path, bool checkHost)
{
byte[] bytes;
// 此 FileStream 的構(gòu)造函數(shù)不是 public ,開發(fā)者不能使用
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;
}這段說明我們可以放心使用 如果我們手動 .NET 文件流緩存大小默認(rèn)是 internal const int DefaultBufferSize = 4096; 這段代碼在 File 類中定義,開發(fā)者不能設(shè)置緩存塊的大小,大多數(shù)情況下,4k 是最優(yōu)的塊大小。 ReadAllBytes 的文件大小上限是 2 GB。 3,Debug 、Trace類這兩個類的命名空間為 Debug 中的所有函數(shù)都不會在 Release 中有效,并且所有輸出流不會在控制臺顯示,必須注冊偵聽器才能讀取這些流。 Debug 可以打印調(diào)試信息并使用斷言檢查邏輯,使代碼更可靠,而不會影響發(fā)運(yùn)產(chǎn)品的性能和代碼大小。 這類輸出方法有 Write 、WriteLine 、 WriteIf 和 WriteLineIf 等,這里輸出不會直接打印到控制臺。 如需將調(diào)試信息打印到控制臺,可以注冊偵聽器: ConsoleTraceListener console = new ConsoleTraceListener(); Trace.Listeners.Add(console); 注意, .NET Core 2.x 以上 Debug 沒有 Listeners ,因?yàn)?Debug 使用的是 Trace 的偵聽器。 我們可以給 Trace.Listeners 注冊偵聽器,這樣相對于 Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.WriteLine("aa");.NET Core 中的監(jiān)聽器都繼承了 TraceListener,如 TextWriterTraceListener、ConsoleTraceListener、DefaultTraceListener。 如果需要輸出到文件中,可以自行繼承 示例: TraceListener listener = new DelimitedListTraceListener(@"C:\debugfile.txt");
// Add listener.
Debug.Listeners.Add(listener);
// Write and flush.
Debug.WriteLine("Welcome");處理上述方法輸出控制臺,也可以使用 ConsoleTraceListener console=... ...Listeners.Add(console); // 等效于 var console = new TextWriterTraceListener(Console.Out) 為了格式化輸出流,可以使用 一下屬性控制排版:
// 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
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.
在 IDE 中運(yùn)行程序時,使用 在非 IDE 環(huán)境下,程序會輸出一些信息,但不會有中斷效果。 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 個人認(rèn)為,可以將 Debug、Trace 引入項(xiàng)目中,與日志組件配合使用。Debug、Trace 用于記錄程序運(yùn)行的診斷信息,便于日后排查程序問題;日志用于記錄業(yè)務(wù)過程,數(shù)據(jù)信息等。
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,條件編譯
如果使用特性進(jìn)行條件編譯標(biāo)記,在開發(fā)過程中就可以留意到這部分代碼。 [Conditional("DEBUG")]例如,當(dāng)使用修改所有引用-修改一個類成員變量或者靜態(tài)變量名稱時,
代碼片段只能使用 5,MethodImpl 特性此特性在 System.Runtime.CompilerServices 命名空間中,指定如何實(shí)現(xiàn)方法的詳細(xì)信息。 內(nèi)聯(lián)函數(shù)使用方法可參考 https://www./archives/995 MethodImpl 特性可以影響 JIT 編譯器的行為。 無法使用 MethodImpl 可以在方法以及構(gòu)造函數(shù)上使用。 MethodImplOptions 用于設(shè)置編譯行為,枚舉值可組合使用,其枚舉說明如下:
意思是說,如果共享的成員已經(jīng)設(shè)置了鎖,那么不應(yīng)該再在 5,CLSCompliantAttribute指示程序元素是否符合公共語言規(guī)范 (CLS)。 CLS規(guī)范可參考: https://docs.microsoft.com/en-us/dotnet/standard/language-independence https://www./publications/standards/Ecma-335.htm 全局開啟方法: 程序目錄下添加一個 AssemblyAttribytes.cs 文件,或者打開 obj 目錄,找到 AssemblyAttributes.cs 結(jié)尾的文件,如 .NETCoreApp,Version=v3.1.AssemblyAttributes.cs,添加: using System;// 這行已經(jīng)有的話不要加 [assembly: CLSCompliant(true)] 之后就可以在代碼中使用 局部開啟: 也可以放在類等成員上使用: [assembly: CLSCompliant(true)] 您可以將特性應(yīng)用于 CLSCompliantAttribute 下列程序元素:程序集、模塊、類、結(jié)構(gòu)、枚舉、構(gòu)造函數(shù)、方法、屬性、字段、事件、接口、委托、參數(shù)和返回值。 但是,CLS 遵從性的概念僅適用于程序集、模塊、類型和類型的成員。 程序編譯時默認(rèn)不會檢查代碼是否符合 CLS 要求,但是如果你的可以是公開的(代碼共享、Nuget 發(fā)布等),則建議使用使用 在團(tuán)隊(duì)開發(fā)中以及內(nèi)部共享代碼時,高質(zhì)量的代碼尤為重要,所以有必要使用工具檢查代碼,如 roslyn 靜態(tài)分析、sonar 掃描等,也可以使用上面的特性,自動使用 CLS 檢查。 CLS 部分要求:
我們可以編譯以下代碼,嘗試使用 [assembly: CLSCompliant(true)]
[CLSCompliant(true)]
public class Test
{
public void MyMethod()
{
}
public void MYMETHOD()
{
}
}IDE 中會警告:warning CS3005: 僅大小寫不同的標(biāo)識符“Test.MYMETHOD()”不符合 CLS,編譯時也會提示 Warn。當(dāng)然,不會阻止編譯,也不會影響程序運(yùn)行。 總之,如果要標(biāo)記一個程序集 CLS 規(guī)范,可以使用
如果偏偏要寫不符合規(guī)范的代碼,則可以使用 6,必要時自定義類型別名C# 也可以定義類型別名。 using intbyte = System.Int32; using intkb = System.Int32; using intmb = System.Int32; using intgb = System.Int32; using inttb = System.Int32; byte[] fileByte = File.ReadAllBytes("./666.txt");
intmb size = fileByte.Length / 1024;一些情況下,使用別名可以提高代碼可讀性。真實(shí)項(xiàng)目不要使用以上代碼,我只是寫個示例,這并不是合適的應(yīng)用場景。 今天學(xué)習(xí) Runtime 的代碼就到這里為止。 |
|
|