前不久Core誕生時候,那個時候我也在項目上沒時間去嘗那青澀的味道。今天剛剛裝上2017就等不及的試了一下。
先創建了一個控制台的應用程序,然后在Main()方法中寫了幾句話,就等不及的Ctrl+F5,想看看是啥效果。
1 using System; 2 3 namespace TestCoreConsole 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Console.WriteLine("這是中文輸出"); 10 Console.WriteLine(Console.ReadLine()); 11 } 12 } 13 }
發現我輸出的中文竟然亂碼了,我當時想到應該是編碼的問題,然后去調整VS的編碼類型,也沒有解決中文亂碼的問題。
后來我調用了一次Encoding的GetEncoding獲取中文編碼類型
結果拋出:Unhandled Exception: System.ArgumentException: 'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.Parameter name: name
異常信息中提到了Encodeing.RegisterProvider,后來一看原來.NET Core 在默認情況下是沒有注冊EncodeProvider,需要我們們手動自己去注冊。擼起袖子就注冊。
需要先添加CodePagesEncoingProvider的引用,在NuGet包System.Text.Encoding.CodePages里面
using System; using System.Text; namespace TestCoreConsole { class Program { static void Main(string[] args) {
//注冊EncodeProvider Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.WriteLine("這是中文輸出"); Console.WriteLine("This is english output."); Console.WriteLine(Console.ReadLine()); } } }
再次Ctrl+F5 就好了
這樣問題是.net core 的模塊化的設計原則,但是這樣是否能做到跟2015以及之前的離線式的開發?這個問題先留着,日后研究。