C,运算符和类型强制转换.pptVIP

  • 9
  • 0
  • 约1.78万字
  • 约 54页
  • 2017-02-04 发布于江苏
  • 举报
* * * * * * * * * * * * * * * * * * * * * * * * 6. User-defined Casts Multiple casting (cont.) public static implicit operator Currency (uint value) { return new Currency(value, 0); } public static implicit operator uint (Currency value) { return value.Dollars; } Currency balance = new Currency(50, 35); ulong bal = (ulong) balance; Currency→uint→ulong or Currency→float→ulong 6. User-defined Casts Multiple casting (cont.) Currency balance = new Currency(50,35); Console.WriteLine(balance); Console.WriteLine(“balance is “ + balance); Console.WriteLine(“balance is (using ToString()) “ + balance.ToString()); uint balance3 = (uint) balance; Console.WriteLine(“Converting to uint gives “ + balance3); 50 balance is $50.35 balance is (using ToString()) $50.35 Converting to uint gives 50 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 3. Boxing and Unboxing Warnings The type the variable uses to box will remain the same when unboxing the same variable. int x = 5; // declaring System.Int32 double y = 0; // declaring System.Double object o = x; // Implicit Boxing y = (double)o; // Explicit Unboxing to double y = (double)(int)o; // Explicit Unboxing and then casting to double 3. Boxing and Unboxing Warnings When unboxing, you have to be careful that the receiving value variable has enough room to store all the bytes in the value being unboxed. C#’s ints are only 32 bits long, so unboxing a long value (64 bits) into an int as shown here will result in an InvalidCastException. long myLongNumber = 333333423; object myObject = (object)myLongNumber; int myIntNumber = (int)myObject; 3. Boxing and Unboxing Advantage: Overload function Private void DisposeFunc(object o) { switch(o.getType().ToString()) { case “A”: ? //handle A; case “B”: ? //handle B; case “C”: ? //handle C; … } } 4. Comparing Objects for Equality Comparing reference types for equality ReferenceEquals() Virtual Equals() Static Equals() Comparison operator (==) Comparing value type

文档评论(0)

1亿VIP精品文档

相关文档