程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 圖解C# Console 輸出和Console相關編程復習總結

圖解C# Console 輸出和Console相關編程復習總結

編輯:C#入門知識

圖解C# Console 輸出和Console相關編程復習總結


1 基本控制台輸出

首先進入SharpDevelop ,新建一個控制台工程;

SharpDevelop簡介:

http://blog.csdn.net/bcbobo21cn/article/details/44200205

 

\

 

using System;

namespace conwrdemo
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
			
			// TODO: Implement Functionality Here
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}

結果;

 

\

 

2Write()和WriteLine()的區別

Write()和WriteLine()都是System.Console提供的方法,兩者主要用來將輸出流由指定的輸出裝置(默認為屏幕)顯示出來.兩著間的差異在Console.WriteLine()方法是將要輸出的字符串與換行控制字符一起輸出,當次語句執行完畢時,光標會移到目前輸出字符串的下一行.至於Console.Write()方法,光標會停在輸出字符串的最後一個字符後,不會移動到下一行。

 

 

3 輸出格式詳解

格式項都采用如下形式:
{index[,alignment][:formatString]}

其中"index"指索引占位符;
",alignment"對齊方式,以","為標記;
":formatString"是對輸出格式的限定,以":"為標記。

alignment:可選,是一個帶符號的整數,指示首選的格式化字段寬度。如果“對齊”值小於格式化字符串的長度,“對齊”會被忽略,並且使用格式化字符串的長度作為字段寬度。如果“對齊”為正數,字段的格式化數據為右對齊;如果“對齊”為負數,字段的格式化數據為左對齊。如果需要填充,則使用空白。如果指定“對齊”,就需要使用逗號。

formatString:由標准或自定義格式說明符組成.

 

 

 

using System;

namespace conwrdemo2
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("各種數據格式的輸出:");
			// Console.WriteLine 中各種數據格式的輸出
            Console.WriteLine("{0, 8 :C}", 2);     // $2.00
            Console.WriteLine("{0, 8 :C3}", 2);    // $2.000
            Console.WriteLine("{0 :D3}", 2);       // 002
            Console.WriteLine("{0 :E}", 2);        // 2.000000E+000
            Console.WriteLine("{0 :G}", 2);        // 2
            Console.WriteLine("{0 :N}", 2500000.00);    // 2,500,00.00
            Console.WriteLine("{0 :x4}", 12);      // 000c
            Console.WriteLine("{0, 2 :x}", 12);    //  c
            Console.WriteLine("{0 :000.000}", 12.23);   // 012.230
            Console.WriteLine("{0 :r}", 15.62);    // 15.62
            Console.WriteLine("{0 :d}", System.DateTime.Now);    // 2012-3-27
            Console.WriteLine("{0 :D}", System.DateTime.Now);    // 2012年3月27日
 
            Console.WriteLine("{0 :t}", System.DateTime.Now);    // 11:43
            Console.WriteLine("{0 :T}", System.DateTime.Now);    // 11:43:34
 
            Console.WriteLine("{0 :f}", System.DateTime.Now);    // 2012年3月27日 11:43
            Console.WriteLine("{0 :F}", System.DateTime.Now);    // 2012年3月27日 11:43:34
 
            Console.WriteLine("{0 :g}", System.DateTime.Now);    // 2012-3-27 11:43
            Console.WriteLine("{0 :G}", System.DateTime.Now);    // 2012-3-27 11:43:34
 
            Console.WriteLine("{0 :M}", System.DateTime.Now);    // 3月27日
            Console.WriteLine("{0 :r}", System.DateTime.Now);// Tue, 27 Mar 2012 11:43:34 GMT
            Console.WriteLine("{0 :s}", System.DateTime.Now);    // 2012-03-27T11:43:34
            Console.WriteLine("{0 :u}", System.DateTime.Now);    // 2012-03-27 11:43:34Z
            Console.WriteLine("{0 :U}", System.DateTime.Now);    // 2012年3月27日 3:43:34
            Console.WriteLine("{0 :Y}", System.DateTime.Now);    // 2012年3月
 
            Console.WriteLine("{0 :dd}", System.DateTime.Now);   // 27
            Console.WriteLine("{0 :ddd}", System.DateTime.Now);  // 二
            Console.WriteLine("{0 :dddd}", System.DateTime.Now); // 星期二
 
            Console.WriteLine("{0 :f}", System.DateTime.Now);    // 2012年3月27日 11:46
            Console.WriteLine("{0 :ff}", System.DateTime.Now);   // 18
            Console.WriteLine("{0 :fff}", System.DateTime.Now);  // 187
            Console.WriteLine("{0 :ffff}", System.DateTime.Now); // 1875
            Console.WriteLine("{0 :fffff}", System.DateTime.Now); // 18750
 
            Console.WriteLine("{0 :gg}", System.DateTime.Now);   // 公元
            Console.WriteLine("{0 :ggg}", System.DateTime.Now);  // 公元
            Console.WriteLine("{0 :gggg}", System.DateTime.Now); // 公元
            Console.WriteLine("{0 :ggggg}", System.DateTime.Now);     // 公元
            Console.WriteLine("{0 :gggggg}", System.DateTime.Now);    // 公元
 
            Console.WriteLine("{0 :hh}", System.DateTime.Now);   // 11
            Console.WriteLine("{0 :HH}", System.DateTime.Now);   // 11
 
            Console.WriteLine("{0 :mm}", System.DateTime.Now);   // 50
            Console.WriteLine("{0 :MM}", System.DateTime.Now);   // 03
 
            Console.WriteLine("{0 :MMM}", System.DateTime.Now);  // 三月
            Console.WriteLine("{0 :MMMM}", System.DateTime.Now); // 三月
 
            Console.WriteLine("{0 :ss}", System.DateTime.Now);   // 43
            Console.WriteLine("{0 :tt}", System.DateTime.Now);   // 上午
 
            Console.WriteLine("{0 :yy}", System.DateTime.Now);   // 12
            Console.WriteLine("{0 :yyyy}", System.DateTime.Now); // 2012
            Console.WriteLine("{0 :zz}", System.DateTime.Now);   // +08
            Console.WriteLine("{0 :zzz}", System.DateTime.Now);  // +08:00
            Console.WriteLine("{0 :hh:mm:ss}", System.DateTime.Now);  // 11:43:34
            Console.WriteLine("{0 :dd/MM/yyyy}", System.DateTime.Now); // 27-03-2012
			
			// TODO: Implement Functionality Here
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}


 

\

以下是關於輸出格式的示例,該資料來自網上;

\

 

\

 

\

 

4 WriteLine()的各種重載

命名空間: System
程序集: mscorlib(mscorlib.dll 中)

重載列表
名稱 說明
WriteLine()
將當前行終止符寫入標准輸出流。
WriteLine(Boolean)
將指定布爾值的文本表示形式(後跟當前行終止符)寫入標准輸出流。
WriteLine(Char)
Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream.
WriteLine(Char[])
將指定的 Unicode 字符數組(後跟當前行終止符)寫入標准輸出流。
WriteLine(Char[], Int32, Int32)
將指定的 Unicode 字符子數組(後跟當前行終止符)寫入標准輸出流。
WriteLine(Decimal)
將指定的 Decimal 值的文本表示形式(後跟當前行終止符)寫入標准輸出流。
WriteLine(Double)
將指定的雙精度浮點值的文本表示形式(後跟當前行終止符)寫入標准輸出流。
WriteLine(Int32)
將指定的 32 位有符號整數值的文本表示(後跟當前行的結束符)寫入標准輸出流。
WriteLine(Int64)
將指定的 64 位有符號整數值的文本表示(後跟當前行的結束符)寫入標准輸出流。
WriteLine(Object)
Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.
WriteLine(Single)
將指定的單精度浮點值的文本表示形式(後跟當前行終止符)寫入標准輸出流。
WriteLine(String)
將指定的字符串值(後跟當前行終止符)寫入標准輸出流。
WriteLine(String, Object)
Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine(String, Object, Object)
Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine(String, Object, Object, Object)
使用指定的格式信息,將指定對象的文本表示形式(後跟當前行終止符)寫入標准輸出流。
WriteLine(String, Object, Object, Object, Object)
使用指定的格式信息,將指定的對象和可變長度參數列表(後跟當前行終止符)的文本表示形式寫入標准輸出流。
WriteLine(String, Object[])
使用指定的格式信息,將指定的對象數組(後跟當前行終止符)的文本表示形式寫入標准輸出流。
WriteLine(UInt32)
Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream.
WriteLine(UInt64)
Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream.

 

 

5 C# Console類的具體用法

Console.Write 表示向控制台直接寫入字符串,不進行換行,可繼續接著前面的字符寫入。
Console.WriteLine 表示向控制台寫入字符串後換行。
Console.Read 表示從控制台讀取字符串,不換行。
Console.ReadLine 表示從控制台讀取字符串後進行換行。
Console.ReadKey 獲取用戶按下的下一個字符或功能鍵,按下的鍵顯示在控制台窗口中。
Console.Beep 通過控制台揚聲器播放提示音。
Console.Clear 清除控制台緩沖區和相應的控制台窗口的顯示信息。

輸出到控制台
Console.WriteLine();
Console.Write();
Console.WriteLine(輸出的值);
Console.Write(輸出的值);
Console.WriteLine("輸出的格式字符串",變量列表);
Console.Write("輸出的格式字符串",變量列表);

Console.WriteLine("鹿鼎記中{0}的妻子有{1},{2},{3}等7個",strName[0],strName[1],strName[2],strName[3]);
這種方式中包含兩個參數:“格式字符串”和變量列表。“鹿鼎記中{0}的妻子有{1},{2},{3}等7個”這是格式字符串,{0}、{1}、{2}、{3}叫做占位符,代表後面依次排列的變量表,0對應變量列表的第一個變量,1對應變量列表的第2個變量,依次類推,完成輸出。

從控制台輸入
Console.ReadLine();
這一句代碼返回一個字符串型數據,可以把它直接賦值給字符串變量,如:
string strname=Console.ReadLine();
有時需要從控制台輸入數字,就用到前面介紹的內容,數據轉換,如:
int num=int.Pares(Console.ReadLine());
int num=Convert.ToInt32(Console.ReadLine());
上面兩句代碼效果相同,可以根據自己的習慣選擇任意一種。


注意:
Console.ReadLine()和Console.Read()的輸入結果完全不同,不能混用。
Console.Read(),返回值為首字符的ASCII碼
Console.ReadLine(),返回值為字符串
也就是說read方法只能讀取第一個字符,而ReadLine能讀多個字符也可以換行讀取


Console.ReadKey()的作用,read是從控制台讀取,key表示按下鍵盤,那麼組合在一起的意思就是獲取用戶按下功能鍵顯示在窗口中,用在前面的代碼起到窗口暫停的功能,在調試狀態下,只有按下任意鍵後窗口才會關閉。

 

控制台輸入輸出示例;

 

using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;
namespace ConsoleTest
{
class ConsoleTest
{
static void Main(string[] args)
{
Console.WriteLine("請輸入兩個學生的名字");
string name1=Console.ReadLine();
string name2=Console.ReadLine();
Console.WriteLine("請輸入兩個學生的成績");
int score1=int.Parse(Console.ReadLine());
int score2=int.Parse(Console.ReadLine());
Console.WriteLine("第一個學生的姓名{0},成績{1}",name1,score1);
Console.WriteLine("第二個學生的姓名{0},成績{1}",name2,score2);
Console.ReadKey();
}
}
}

 

 

\

 

6 調試的控制台輸出

窗口程序用Debug.WriteLine
按f5調試運行
輸出結果在“輸出”窗格,視圖-窗口-輸出可以打開它。

新建一個Winform項目,在按鈕單擊事件輸入如下圖代碼;

Debug.WriteLine(str1);

啟動調試;單擊按鈕;str1的值在Output窗口輸出;

\

7 更改控制台窗口大小、字體顏色、獲得行號

using System;

namespace conwrdemo5
{
	class Program
	{
		public static void Main(string[] args)
		{
			// TODO: Implement Functionality Here
			Console.WriteLine(Console.WindowHeight);
            Console.WriteLine(Console.BufferHeight);
            Console.ReadKey();
            Console.Title = "Test";//設置窗口標題
            Console.WindowWidth = 40;
            Console.WindowHeight=20;
            Console.BufferHeight = 20;
            Console.WriteLine(Console.WindowWidth);
            Console.WriteLine(Console.WindowHeight);
            Console.WriteLine("---------------------");
            Console.WriteLine(Console.BufferWidth);
            Console.WriteLine(Console.BufferHeight);
            
            Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
						
            Console.BackgroundColor = ConsoleColor.Blue; //設置背景色
            Console.ForegroundColor = ConsoleColor.White; //設置前景色,即字體顏色
            Console.WriteLine("第一行白藍.");
            Console.ResetColor(); //將控制台的前景色和背景色設為默認值
            Console.BackgroundColor = ConsoleColor.Green;
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            string str = "第三行 綠暗綠";
            Console.WriteLine(str.PadRight(Console.BufferWidth - (str.Length % Console.BufferWidth))); //設置一整行的背景色
            Console.ResetColor();
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
			
			//計算當前光標所在的行數,針對於Console.BufferHeight的值
			ShowColor();
            int m = Console.CursorTop;//查看當前行號Console.BufferHeight 
            Console.ReadKey();
            
            Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
            
		}
		
		//顯示出console中支持的背景色及前景色

        static void ShowColor()
        {
            Type type = typeof(ConsoleColor);
            Console.ForegroundColor = ConsoleColor.White;
            foreach (string name in Enum.GetNames(type))
            {
                Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, name);
                Console.WriteLine(name);
            }

            Console.BackgroundColor = ConsoleColor.Black;
            foreach (string name in Enum.GetNames(type))
            {
                Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, name);
                Console.WriteLine(name);
            }

            foreach (string bc in Enum.GetNames(type))
            {
                Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, bc);
                foreach (string fc in Enum.GetNames(type))
                {
                    Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, fc);
                    Console.WriteLine("bc="+bc+",fc="+fc);
                }
                Console.WriteLine();
            }
        }
	}
}

 

 

\

 

\

 

\

Console.BufferHeight 屬性:
The current height, in rows, of the buffer area.

8 Winform啟動控制台並執行命令

 

Process pro = new Process();
			pro.StartInfo.FileName = "cmd.exe";
			//pro.StartInfo.Arguments = @"C:\Windows\System32";
			pro.StartInfo.UseShellExecute=false;
			pro.StartInfo.RedirectStandardInput=true;
			pro.StartInfo.RedirectStandardOutput=true;
			pro.StartInfo.RedirectStandardError=true;
			pro.StartInfo.CreateNoWindow=false;
			
			pro.Start();	
			pro.StandardInput.WriteLine("ver");
			//pro.StandardInput.WriteLine("exit");
			string rs=pro.StandardOutput.ReadToEnd();


 

代碼如下,啟動了控制台,命令沒有執行;下次再搞;

\

 

9 另一個設置控制台字體顏色程序

 

using System;

namespace conwrdemo7
{
	class Program
	{
		public static void Main(string[] args)
		{
			String nl = Environment.NewLine;
	        String[] colorNames = Enum.GetNames(typeof(ConsoleColor));
	
	        Console.WriteLine("{0}All the foreground colors on a constant black background.", nl);
	        Console.WriteLine("  (Black on black is not readable.){0}", nl);
	
	        for (int x = 0; x < colorNames.Length; x++)
	        {
	            Console.Write("{0,2}: ", x);
	            Console.BackgroundColor = ConsoleColor.Black;
	            Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);
	            Console.Write("This is foreground color {0}.", colorNames[x]);
	            Console.ResetColor();
	            Console.WriteLine();
	        }
	
	        Console.ForegroundColor = ConsoleColor.Yellow;
	        Console.Write("/x01");
	        Console.Write("/u0001");
	        Console.Write("/001");
	        Console.Write("/x10");
	        Console.Write("/u0010");
	        Console.Write("/020");
	
	        Console.WriteLine();
	        Console.Write("{0,-50}", "Class1.TestMethod1");
	        Console.Write("{0,-2}","/x10");
	        Console.ForegroundColor = ConsoleColor.Green;
	        Console.WriteLine("Pass");
	
	        Console.WriteLine();
	        Console.ForegroundColor = ConsoleColor.Yellow;
	        Console.Write("{0,-50}", "Class1.TestMethod2");
	        Console.Write("{0,-2}", "/x10");
	        Console.ForegroundColor = ConsoleColor.Red;
	        Console.WriteLine("Failed");
	
	        Console.ReadLine();
		}
	}
}


 

\

 

上述工程,一共7個小項目;

\

下載地址

http://pan.baidu.com/s/1o8qyWLs

文件名

conwrdemo

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved