C#中的checked与implicit,explicit

默认情况下,如果表达式仅包含常数值,且产生的值在目标类型范围之外,则它会导致编译器错误。
如果表达式包含一个或多个非常数值,则编译器不检测溢出。

在下面的示例中,计算赋给 i2 的表达式不会导致编译器错误。

int i2 = 2147483647 + ten;

checked

{   

     int i3 = 2147483647 + ten;   

     Console.WriteLine(i3);

}

可以使用 unchecked 关键字阻止溢出检查。

 

explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。
转换运算符可以是 explicit,也可以是 implicit
隐式转换运算符更容易使用,但是如果您希望运算符的用户能够意识到正在进行转换,则显式运算符很有用。
下面是一个综合的例子:
struct Currency
{
public uint Dollars;
public ushort Cents;
      public Currency(uint dollars, ushort cents)
{
this.Dollars = dollars;
this.Cents = cents;
}
public override string ToString()
{
return string.Format("${0}.{1,-2:00}", Dollars,Cents);
}

public static string GetCurrencyUnit()
{
return "Dollar";
}
public static explicit operator Currency (float value)//???
{
checked
{
uint dollars =(uint)value;
ushort cents =(ushort)((value-dollars)*100);
return new Currency(dollars,cents);
}
}
public static implicit operator float (Currency value)
{
return value.Dollars + (value.Cents/100.0f);
}
public static implicit operator Currency (uint value)
{
return new Currency(value, 0);
}
public static implicit operator uint (Currency value)
{
return value.Dollars;
}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值