参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P128
学习目的:掌握控制台输入函数Read、ReadKey、ReadLine和输出函数Write、WriteLine函数的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Example4_1
{
class Program
{
public class Product
{
public int No { get; set; } //产品编号
public string Name { get; set; } //产品名称
public DateTime ProductDate { get; set; } //生产时间
//重写ToString方法,将类的三个属性连接成一个字符串输出
public override string ToString()
{
// return base.ToString();
string str = "编号:" + No.ToString() + ",产品名称:" +
Name.ToString() + ",日期:" + ProductDate.ToShortDateString();
return str;
}
}
static void Main(string[] args)
{
Product p = new Product();
p.No = 101;
p.Name = "洗衣机";
p.ProductDate = new DateTime(2014, 3, 15);
//或者建立实例时直接赋值
Product p1 = new Product()
{
No = 102,
Name = "电视机",
ProductDate = new DateTime(2015, 6, 22)
};
//输出
WriteLine("{0}", p.ToString());
WriteLine("{0}", p1.ToString());
WriteLine(p);
/*
//---------------演示Read方法的使用-----------
int input = 0;
while(input != -1)
{
input = Read();
//过滤换行符和回车符
if ((input !=13) && (input !=10))
{
//将读书的整数值转化为字符并输出
Console.WriteLine("输入了字符:{0}({1})", (char)input, input);
}
if (input == 113) //按q键退出(只要字符串中包含q就退出)
break;
}
*/
//----------------ReadKey的使用----------
//Readkey读取用户输入的字符,返回一个ConsoleKeyInfo结构的实例,
//通过ConsoleKeyInfo结构的几个水泥管可以获取有关按键的信息,Read更方便
ConsoleKeyInfo keyInfo;
do
{
keyInfo = ReadKey();
WriteLine("您按下了{0}键", keyInfo.Key);
}
//按下Escape键退出循环
while (keyInfo.Key != ConsoleKey.Escape);
// ReadKey();
}
}
}
运行结果如下: