Fork me on GitHub

【Helper】习惯&规则

强制转换和as、is运算符

   强制转换运算符使用规则

  • 把一种引用类型转换成另一种引用类型。
  • 把一种值类型转换成另一种值类型。
  • 执行装箱货拆箱转换
  • 调用一种用户自定义的转换。

   as运算符使用规则

  • 不能接受抛出InvalidCastException异常。如果不能执行强转,as运算符将代之以返回null。
  • 把一种引用类型转换成另一种引用类型。
  • You are not casting a value type to a value type. The cast operator must be used
    in this case。(说实话这句话不太理解)(明白了,这是不能使用的情况)
    翻译是:不会把一种值类型转换成另一种值类型。在这种情况下必须使用强制转换运算符。
  • 执行装箱操作。
  • You are not performing an unboxing conversion. The cast operator must be used
    in this case unless the unboxing is to a nullable type.(这句话不太理解)(同上)
    翻译是:不会执行拆箱转换。在这种情况下必须使用强制转换运算符,除非拆箱是一种可空类型。
    原因:有些类型是不能空的。比如int,你不能把null赋值给int。
    方法:使用可空类型int?。
  • 不会调用一种用户自定义的转换。在这种情况下必须使用强制转换运算符。
  • You are performing a cast to a type parameter T that can be only a reference
    type. This is because a null may be returned after evaluating this expression.
    翻译是:强制转换到只能为引用类型的类型参数T。这是由于在对该表达式求值时可能返回null。
    原因:T可能是值类型。
    方法:public class TestAsOp<T> where T:class {}

   is运算符使用规则

  • 在尝试使用as之前,需要快速确定使用as会不会返回null。
  • 不需要转换,仅仅确定是否可以转换成某种类型。
  • 不能接受抛出InvalidCastException异常。
  • 不会把一种值类型转换成另一种值类型。在这种情况下必须使用强制转换运算符。
  • 不会调用一种用户定义的转换。is将总返回一个false,而不管是否可转换。
posted @ 2010-01-03 16:24  idoku  阅读(174)  评论(0编辑  收藏  举报