版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、7Operators and Casts,Shuai L 2012.8.29,0. Introduction,Operators (Chapter 7.1) (Primitive) Type Conversions (Chapter 7.2.1) Boxing and Unboxing (Chapter 7.2.2) Comparing Objects for Equality (Chapter 7.3) Operator Overloading (Chapter 7.4) User-defined Casts (Chapter 7.5),1. Operators,1. Operators,1
2、. Operators,Note that four specific operators (sizeof, *, -, and checked b+; Console.WriteLine(b.ToString();,Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow at Wrox.ProCSharp.Basics.OverflowTest.Main(String args),1. Operators,The checked and unchecked oper
3、ators byte b = 255; unchecked b+; Console.WriteLine(b.ToString();,You can enforce overflow checking for all unmarked code in your program by specifying the /checked compiler option.,1. Operators,The is operator The is operator allows you to check whether an object is compatible with a specific type.
4、 The phrase “ is compatible ” means that an object either is of that type or is derived from that type. int i = 10; if (i is object) Console.WriteLine(i is an object); ,1. Operators,The as operator The as operator is used to perform explicit type conversions of reference types. object o1 = Some Stri
5、ng; object o2 = 5; string s1 = o1 as string; / s1 = Some String string s2 = o2 as string; / s2 = null The as operator allows you to perform a safe type conversion in a single step without the need to first test the type using the is operator and then perform the conversion.,1. Operators,The typeof o
6、perator The typeof operator returns a System.Type object representing a specified type. typeof(string) will return a Type object representing the System.String type.,2. (Primitive) Type Conversions,byte value1 = 10; byte value2 = 23; byte total; total = value1 + value2; Console.WriteLine(total);,Can
7、not implicitly convert type int to byte ,2. (Primitive) Type Conversions,Implicit conversions byte value1 = 10; byte value2 = 23; long total;/ this will compile fine total = value1 + value2; Console.WriteLine(total);,2. (Primitive) Type Conversions,2. (Primitive) Type Conversions,Explicit conversion
8、s long val = 30000; int i = (int)val; / A valid cast. The maximum int is 2147483647 long val = 3000000000; int i = (int)val; / An invalid cast. The maximum int is 2147483647 int i = checked(int)val); ushort c = 43; char symbol = (char)c; Console.WriteLine(symbol);,-1294967296 / 3000000000 2* 2147483
9、648,+,2. (Primitive) Type Conversions,Explicit conversions (cont.) int? a = null; int b = (int)a; / Will throw InvalidOperationException exception int i = 10; string s = i.ToString(); string s = “100”; int i = int.Parse(s); Console.WriteLine(i + 50); / Add 50 to prove it is really an int You cannot
10、directly cast Booleans to any other type or vice versa.,3. Boxing and Unboxing,C# data types Simple predefined types: sbyte, byte, short, ushort, int, uint, long, ulong float, double, decimal, bool, char Complex types: enum, struct, nullablevalue types - object, string, classreference types interfac
11、e, array, delegate,3. Boxing and Unboxing,Boxing and its counterpart Unboxing Allow you to convert value types to reference types and then back to value types. Boxing is the term used to describe the transformation of a value type to a reference type. Basically, the runtime creates a temporary refer
12、ence-type box for the object on the heap.,3. Boxing and Unboxing,Implicit conversion string s = 10.ToString(); / Implicit Boxing int myIntNumber = 20; object myObject = myIntNumber; / Implicit/Explicit Boxing Explicit conversion int x = 10; object o = (object) x; / Explicit Boxing,3. Boxing and Unbo
13、xing,Unboxing is the term used to describe the reverse process, where the value of a previously boxed value type is cast back to a value type. The syntax is similar to explicit type conversions. Explicit conversion int myIntNumber = 20; object myObject = myIntNumber; / Implicit Boxing int mySecondNu
14、mber = (int)myObject; / Explicit Unboxing,3. Boxing and Unboxing,Warnings You cannot implicitly convert a reference type to a value type. int x = 5; object o = x; / Implicit Boxing x = o; / Implicit Unboxing x = (int)o; / Explicit Unboxing You can only unbox a variable that has previously been boxed
15、.,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; / Exp
16、licit 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
17、 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”: /h
18、andle B; case “C”: /handle C; ,4. Comparing Objects for Equality,Comparing reference types for equality ReferenceEquals() Virtual Equals() Static Equals() Comparison operator (=) Comparing value types for equality,4. Comparing Objects for Equality,ReferenceEquals() ReferenceEquals() is a static meth
19、od that tests whether two references refer to the same instance of a class, specifically whether the two references contain the same address in memory. SomeClass x, y; x = new SomeClass(); y = new SomeClass(); bool B1 = ReferenceEquals(null, null); / returns true bool B2 = ReferenceEquals(null,x); /
20、 returns false / returns false because x and y point to different objects bool B3 = ReferenceEquals(x, y);,4. Comparing Objects for Equality,Virtual Equals() The System.Object implementation of the virtual version of Equals() also works by comparing references. However, because this method is virtua
21、l, you can override it in your own classes to compare objects by value.,4. Comparing Objects for Equality,Static Equals() The static version of Equals() takes two parameters and compares them for equality. The static overload first checks whether the references it has been passed are null. If they a
22、re both null, it returns true (because null is considered to be equal to null). If just one of them is null, it returns false. If both references actually refer to something, it calls the virtual instance version of Equals().,4. Comparing Objects for Equality,Comparison operator (=) In most cases, w
23、riting the following means that you are comparing references. bool b = (x = y); / x, y object references It is better to override the comparison operator to perform a value comparison. String class for which Microsoft has overridden this operator to compare the contents of the strings rather than th
24、eir references.,4. Comparing Objects for Equality,Comparing value types for equality ReferenceEquals() is used to compare references, Equals() is intended for value comparisons, and the comparison operator is viewed as an intermediate case. Microsoft has already overloaded the instance Equals() meth
25、od in the System.ValueType class to test equality appropriate to value types.,4. Comparing Objects for Equality,Comparing value types for equality ReferenceEquals() always returns false when applied to value types because, to call this method, the value types need to be boxed into objects. bool b =
26、ReferenceEquals(v,v); / v is a variable of some value type For structs, the = operator does not do anything at all by default. Trying to compare two structs to see if they are equal produces a compilation error unless you explicitly overload = to tell the compiler how to perform the comparison.,5. O
27、perator Overloading,struct Vector public double x, y, z; public Vector(double x, double y, double z) this.x = x;this.y = y;this.z = z; public Vector(Vector rhs) x = rhs.x;y = rhs.y;z = rhs.z; public override string ToString() return ( + x + , + y + , + z + )“; public static Vector operator + (Vector
28、 lhs, Vector rhs) /lhs: left-hand side, rhs: right-hand side ,5. Operator Overloading,public static Vector operator + (Vector lhs, Vector rhs) Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; ,5. Operator Overloading,static void Main() Vector v
29、ect1, vect2, vect3; vect1 = new Vector(3.0, 3.0, 1.0); vect2 = new Vector(2.0, - 4.0, - 4.0); vect3 = vect1 + vect2; Console.WriteLine( “ vect1 = “ + vect1.ToString(); Console.WriteLine( “ vect2 = “ + vect2.ToString(); Console.WriteLine( “ vect3 = “ + vect3.ToString(); ,vect1 = ( 3, 3, 1 ) vect2 = (
30、 2, - 4, - 4 ) vect3 = ( 5, - 1, - 3 ),5. Operator Overloading,public static Vector operator * (double lhs, Vector rhs) return new Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); public static Vector operator * (Vector lhs, double rhs) public static Vector operator * (Vector lhs, double rhs) return r
31、hs * lhs; public static double operator * (Vector lhs, Vector rhs) return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; ,5. Operator Overloading,static void Main() Vector vect1, vect2, vect3; vect1 = new Vector(1.0, 1.5, 2.0); vect2 = new Vector(0.0, 0.0, -10.0); vect3 = vect1 + vect2; Console.Writ
32、eLine(“vect1 = ” + vect1); Console.WriteLine(vect2 = + vect2); Console.WriteLine(vect3 = vect1 + vect2 = + vect3); ,vect1 = ( 1, 1.5, 2 ) vect2 = ( 0, 0, -10 ) vect3 = vect1 + vect2 = ( 1, 1.5, -8 ),5. Operator Overloading,Console.WriteLine(2*vect3 = + 2*vect3); vect3 += vect2; Console.WriteLine(vec
33、t3+=vect2 gives + vect3); vect3 = vect1*2; Console.WriteLine(Setting vect3=vect1*2 gives + vect3); double dot = vect1*vect3; Console.WriteLine(vect1*vect3 = + dot); ,2*vect3 = ( 2, 3, -16 ) vect3+=vect2 gives ( 1, 1.5, -18 ) Setting vect3=vect1*2 gives ( 2, 3, 4 ) vect1*vect3 = 14.5,vect1 = ( 1, 1.5
34、, 2 ) vect2 = ( 0, 0, -10 ) vect3 = vect1 + vect2 = ( 1, 1.5, -8 ),5. Operator Overloading,public static bool operator = (Vector lhs, Vector rhs) if (lhs.x = rhs.x It requires that you overload these operators in pairs.,5. Operator Overloading,static void Main() Vector vect1, vect2, vect3; vect1 = n
35、ew Vector(3.0, 3.0, -10.0); vect2 = new Vector(3.0, 3.0, -10.0); vect3 = new Vector(2.0, 3.0, 6.0); Console.WriteLine(“vect1=vect2 returns ” + (vect1=vect2); /True Console.WriteLine(vect1=vect3 returns + (vect1=vect3); /False Console.WriteLine(vect2=vect3 returns + (vect2=vect3); /False Console.Writ
36、eLine(vect1!=vect2 returns + (vect1!=vect2); /False Console.WriteLine(vect1!=vect3 returns + (vect1!=vect3); /True Console.WriteLine(vect2!=vect3 returns + (vect2!=vect3); /True ,5. Operator Overloading,Warnings If you overload = and !=, you must also override the Equals() and GetHashCode() methods
37、inherited from System.Object; otherwise, youll get a compiler warning. The reasoning is that the Equals() method should implement the same kind of equality logic as the = operator.,5. Operator Overloading,Warnings (cont.),Vectors3.cs(5,11): warning CS0660: Wrox.ProCSharp.OOCSharp.Vector defines oper
38、ator = or operator != but does not override Object.Equals(object o) Vectors3.cs(5,11): warning CS0661: Wrox.ProCSharp.OOCSharp.Vector defines operator = or operator != but does not override Object.GetHashCode(),5. Operator Overloading,Warnings (cont.) Dont be tempted to overload the comparison opera
39、tor by calling the instance version of the Equals() method inherited from System.Object. If you do and then an attempt is made to evaluate (objA = objB), when objA happens to be null, you will get an exception as the .NET runtime tries to evaluate null.Equals(objB).,6. User-defined Casts,struct Curr
40、ency 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); ,6. User-defined Casts,public static implicit operator float (Currency va
41、lue) return value.Dollars + (value.Cents/100.0f); Currency balance = new Currency(10,50); float f = balance; / f = 10.5 public static explicit operator Currency (float value) uint dollars = (uint)value; ushort cents = (ushort)(value - dollars) * 100); return new Currency(dollars, cents); float amoun
42、t = 45.63f; Currency amount2 = (Currency)amount; Currency amount2 = amount; / wrong, implicit cast,6. User-defined Casts,static void Main() Currency balance = new Currency(50,35); Console.WriteLine(balance); Console.WriteLine(“balance is “ + balance); Console.WriteLine(“balance is (using ToString()
43、“ + balance.ToString(); float balance2= balance; Console.WriteLine(“After converting to float, = “ + balance2); balance = (Currency) balance2; Console.WriteLine(“After converting back to Currency, = “ + balance); ,50.35 Balance is $50.35 Balance is (using ToString() $50.35 After converting to float,
44、 = 50.35 After converting back to Currency, = $50.34,6. User-defined Casts,Console.WriteLine(“Now attempt to convert out of range value of “ + “-$50.50 to a Currency:”); checked balance = (Currency) (-50.50); Console.WriteLine(“Result is “ + balance.ToString(); ,Now attempt to convert out of range v
45、alue of -$50.00 to a Currency: Result is $4294967246.00,50.35 Balance is $50.35 Balance is (using ToString() $50.35 After converting to float, = 50.35 After converting back to Currency, = $50.34,6. User-defined Casts,Casts between classes Casts between base and derived classes Boxing and unboxing ca
46、sts Multiple casting,6. User-defined Casts,Casts between classes You cannot define a cast if one of the classes is derived from the other. The cast must be defined inside the definition of either the source or the destination data type. After you have defined a cast inside one of the classes, you ca
47、nnot also define the same cast inside the other class. public static explicit operator D(C value) public static explicit operator C(D value) ,6. User-defined Casts,Casts between base and derived classes A base class reference can refer to a derived class instance. MyDerived derivedObject = new MyDer
48、ived(); MyBase baseCopy = derivedObject; MyBase derivedObject = new MyDerived(); MyBase baseObject = new MyBase(); MyDerived derivedCopy1 = (MyDerived) derivedObject; / OK MyDerived derivedCopy2 = (MyDerived) baseObject; / Throws exception,6. User-defined Casts,Casts between base and derived classes
49、 (cont.) class DerivedClass: BaseClass public DerivedClass(BaseClass rhs) / initialize object from the Base instance / etc.,6. User-defined Casts,Boxing and unboxing casts When you originally defined the Currency struct, the .NET Framework implicitly supplied another (hidden) class, a boxed Currency class, which contains all the same fields as the Currency struct, but it is a reference type, stored on the heap. When you implicitly cast Currency to object, a boxed Currency instance
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 禽蛋供应合同模板
- 独栋别墅合同范例
- 煮饭阿姨合同范本
- 电梯广告分租合同模板
- 二零二四年度文化传媒公司内容制作与发布合同3篇
- 2024年度智慧城市基础设施建设分包合同2篇
- 林地除草2024年度承包合同样本
- 物联网设备销售合同范例
- 2024年度新能源研发与专利许可合同3篇
- 精准扶贫项目合作合同模板
- 电力安全事故典型案例分析
- 2024年四川省宜宾市中考地理试卷(含答案与解析)
- 电力设备预防性试验规程
- 4.3《课间》 (教案)-2024-2025学年一年级上册数学北师大版
- GB/T 44312-2024巡检机器人集中监控系统技术要求
- 福建省历年中考语文现代文阅读真题17篇(含答案)(2003-2022)
- 侵入性操作相关感染防控
- 小学科学评课稿科学课
- 2024全科医学科理论考试试题及答案
- 2024年下半年教师资格考试初中体育与健康学科知识与教学能力测试试卷与参考答案
- 语文教师职业生涯规划
评论
0/150
提交评论