.NET CORE 怎么样从控制台中读取输入流
生活随笔
收集整理的這篇文章主要介紹了
.NET CORE 怎么样从控制台中读取输入流
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
從Console.ReadList/Read 的源碼中,可學習到.NET CORE 是怎么樣來讀取輸入流。
也可以學習到是如何使用P/Invoke來調用系統API
Console.ReadList 的源碼為
[MethodImplAttribute(MethodImplOptions.NoInlining)]public static string ReadLine(){return In.ReadLine();}其中In為。
internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class =>LazyInitializer.EnsureInitialized(ref field, ref InternalSyncObject, initializer);public static TextReader In => EnsureInitialized(ref s_in, () => ConsolePal.GetOrCreateReader());可以看到他是個TextRead
internal static TextReader GetOrCreateReader(){Stream inputStream = OpenStandardInput();return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ?StreamReader.Null :new StreamReader(stream: inputStream,encoding: new ConsoleEncoding(Console.InputEncoding),detectEncodingFromByteOrderMarks: false,bufferSize: Console.ReadBufferSize,leaveOpen: true));}繼續跳轉,查看方法OpenStandardInput
public static Stream OpenStandardInput(){return GetStandardFile(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE, FileAccess.Read);}繼續看方法
private static Stream GetStandardFile(int handleType, FileAccess access){IntPtr handle = Interop.Kernel32.GetStdHandle(handleType);// 此處源碼一坨注釋被我刪掉了。^_^if (handle == IntPtr.Zero || handle == InvalidHandleValue ||(access != FileAccess.Read && !ConsoleHandleIsWritable(handle))){return Stream.Null;}return new WindowsConsoleStream(handle, access, GetUseFileAPIs(handleType));}哈哈,終于要看到了Interop.Kernel32.GetStdHandle 這個方法就是調用系統API接口函數的方法。
<!-- Windows --><ItemGroup Condition="'$(TargetsWindows)' == 'true'"><Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Kernel32\Interop.GetStdHandle.cs"><Link>Common\CoreLib\Interop\Windows\Interop.GetStdHandle.cs</Link></Compile> </ItemGroup> <!-- Unix --> <ItemGroup Condition=" '$(TargetsUnix)' == 'true'"> </ItemGroup>回到GetStandardFile 中看到返回一個WindowsConsoleStream
useFileAPIs 參數,決定是使用操作系統 ReadFile還是 ReadConsole API。
對于.NET CORE 源碼中有很多 XXXX.Unix.cs,XXXX.Windows.cs
總結
以上是生活随笔為你收集整理的.NET CORE 怎么样从控制台中读取输入流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DevOps之持续集成SonarQube
- 下一篇: 使用VS Code 开发.NET COR