图解C# Console 输出和Console相关编程复习总结

来源:互联网 发布:mac去广告插件 编辑:程序博客网 时间:2024/06/06 00:24

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 HereConsole.Write("Press any key to continue . . . ");Console.ReadKey(true);}}}

结果;


2 Write()和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 HereConsole.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 HereConsole.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


0 0
原创粉丝点击