C#语言有两种不同的常量机制:一种为编译时(compile-time)常量,一种为运行时(runtime)常量。我们说运行时常量优于编译时常量。编译时常量比运行时常量稍微快一点,但却缺乏灵活性。
编译时常量只可以用于基元类型(包括内建的整数类型和浮点类型)、枚举类型或字符串类型。因为只有这些类型才允许我们在初始化器中指定有意义的常量值
private const DateTime _classCreation = new DateTime( 2000, 1, 1, 0, 0, 0 );//编译时常量,报错
只读字段的赋值操作发生在运行时,因此它们具有更多的灵活性。
public static readonly DateTime _classCreation = new DateTime( 2000, 1, 1, 0, 0, 0 );// 运行时常量:
public struct Customer : IComparable
{
private string _name;
public Customer( string name )
{
_name = name;
}
#region IComparable Members
// IComparable.CompareTo()
// 该方法在类型上不够安全。必须检查参数right的运行时类型。
int IComparable.CompareTo( object right )
{
if ( ! ( right is Customer ) )
throw new ArgumentException( "Argument not a customer", "right" );
Customer rightCustomer = ( Customer )right;
return CompareTo( rightCustomer );
}
// 类型安全的CompareTo。其中right是一个Customer或者派生自Customer的类。
public int CompareTo( Customer right )
{
return _name.CompareTo( right._name );
}
#endregion
}
readonly const IComparable
最新推荐文章于 2022-12-25 11:43:34 发布