1.类成员的默认访问修饰语是private
using System;
namespace TimeTest1.src
{
public class Time1:Object
{
private int hour;
private int minute;
private int second;
public Time1()
{
SetTime(0, 0, 0);
}
public void SetTime( int hourValue, int minuteValue, int secondValue )
{
hour = (hourValue >= 0 && hourValue < 24) ? hourValue : 0;
minute = (minuteValue >= 0 && minuteValue < 60) ? minuteValue : 0;
second = (secondValue >= 0 && secondValue < 60) ? secondValue : 0;
}
public string ToUniversalString()
{
return String.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
}
public string ToStandardString()
{
return String.Format("{0}:{1:D2}:{2:D2} {3}",
((hour == 12 || hour == 0) ? 12 : hour % 12),
minute, second, (hour < 12 ? "AM" : "PM"));
}
}
}
using System.Windows.Forms;
using TimeTest1.src;
namespace TimeTest1
{
class Program
{
static void Main(string[] args)
{
Time1 time = new Time1();
string output;
output = "初始24小时制时间为:" +
time.ToUniversalString() +
"初始标准时间为:" +
time.ToStandardString();
time.SetTime(13, 27, 6);
output += "初始24小时制时间为:" +
time.ToUniversalString() +
"初始标准时间为:" +
time.ToStandardString();
MessageBox.Show(output, "Testing Class Time1");
}
}
}
3.对类属性的setter getter:
public int Hour
{
get
{
return hour;
}
set
{
hour = ((value >= 0 && value < 24) ? value : 0);
}
}
4.析构函数:
~Time1()
{
}
//强制垃圾回收
System.GC.Collect();
//等待垃圾回收完成
System.GC.WaitForPendingFinalizers();
(1). static成员不能访问非static成员, 非static 类成员可以访问static 成员。
(2). static方法没有this引用。
//在A类中定义
private static int count;
public static int Count
{
get
{
return count;
}
}
//调用
A.Count;
6.const 和readonly
(1). const成员默认为static 类型因此不需要额外添加static声明,const成员必须在声明时初始化;
(2). readonly成员可以在类构造函数中初始化,不能在初始化之前调用;
(3). 在构造函数中初始化一个static readonly成员时,必须使用static 构造函数;
(4). 二者一旦初始化之后无法修改值。
public const double PI = 3.14159;
public readonly int radius;
public Constants(int radiusValue)
{
radius = radiusValue;
}
7.索引器:
提供类似数组中括号的索引读写值的方法
private int x = 0;
private int y = 0;
public double this[int index]
{
get
{
return index == 0 ? x : y;
}
set
{
if (index == 0)
x = value;
else
y = value;
}
}
public double this[string name]
{
get
{
return name == "x" ? x : y;
}
set
{
if ("name" == "x")
x = value;
else
y = value;
}
}