( 第 2/3 节 )
1定义一个关于网站用户注册信息的类:要求完成的功能有:
1、记录每个用户姓名、年龄(范围是0到100)的信息
2、能统计已经注册用户的人数
3、每个用户的信息需要在创建实例时即填充
4、需要的信息为手动输入
5、通过循环实现可增加多个用户
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
do
{
Console.WriteLine("\n姓名");
string name = Console.ReadLine();
Console.WriteLine("年龄(最大100,超过则按100计算)");
uint age = uint.Parse(Console.ReadLine());
Customer c = new Customer(name, age);
Console.WriteLine("\n信息如下:\n");
Console.WriteLine("姓名:{0}\n年龄:{1}\n当前人数:{2}", c.name, c.age, Customer.number);
Console.WriteLine("是否继续,y为继续,其它退出");
} while (Console.ReadKey().KeyChar == 'y');
Console.ReadKey();
}
}
class Customer
{
public Customer(string p_name, uint p_age)
{
/*访问属性而不是私有变量,防止在初始化数据时
* 导致年龄范围不正常
*/
this.name = p_name;
this.age = p_age;
++_number;
}
~Customer()
{
//实例被销毁时及时减少人数
--_number;
}
private static uint _number = 0;//开始时人数为0
public static uint number
{
/*
* 无set访问器表示此属性是只读的
* 此属性不能由外部代码修改,防止统计错误
*/
get
{
return _number;
}
}
public string name;
private uint _age = 0;
public uint age //属性可以控制年龄在正常范围
{
set
{
if (value > 100)
{
this._age = 100;
}
else
{
this._age = value;
}
}
get
{
return this._age;
}
}
}
}