.NET CORE 怎么样从控制台中读取输入流
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                .NET CORE 怎么样从控制台中读取输入流
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                從Console.ReadList/Read 的源碼中,可學(xué)習(xí)到.NET CORE 是怎么樣來讀取輸入流。
也可以學(xué)習(xí)到是如何使用P/Invoke來調(diào)用系統(tǒng)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));}繼續(xù)跳轉(zhuǎn),查看方法OpenStandardInput
public static Stream OpenStandardInput(){return GetStandardFile(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE, FileAccess.Read);}繼續(xù)看方法
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 這個方法就是調(diào)用系統(tǒng)API接口函數(shù)的方法。
<!-- 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 參數(shù),決定是使用操作系統(tǒng) ReadFile還是 ReadConsole API。
對于.NET CORE 源碼中有很多 XXXX.Unix.cs,XXXX.Windows.cs
總結(jié)
以上是生活随笔為你收集整理的.NET CORE 怎么样从控制台中读取输入流的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: DevOps之持续集成SonarQube
- 下一篇: 使用VS Code 开发.NET COR
