版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度股份代持及風(fēng)險(xiǎn)控制與管理協(xié)議:互聯(lián)網(wǎng)企業(yè)股權(quán)代持合同
- 2025年度演出場(chǎng)地綠化維護(hù)合同大全
- 2025年醫(yī)療衛(wèi)生設(shè)施建設(shè)PPP合同書
- 2024山東記錄媒介的復(fù)制市場(chǎng)前景及投資研究報(bào)告
- 2025年中國保險(xiǎn)代理行業(yè)市場(chǎng)調(diào)研分析及投資戰(zhàn)略咨詢報(bào)告
- 2024醫(yī)藥及醫(yī)療器材專門零售市場(chǎng)前景及投資研究報(bào)告
- 2025年中國NAS網(wǎng)絡(luò)存儲(chǔ)器行業(yè)發(fā)展運(yùn)行現(xiàn)狀及投資戰(zhàn)略規(guī)劃報(bào)告
- 2025年專利許可合同的法律審查
- 2025年中國半夏行業(yè)市場(chǎng)供需格局及投資規(guī)劃建議報(bào)告
- 2025年中國舾裝行業(yè)發(fā)展前景預(yù)測(cè)及投資戰(zhàn)略咨詢報(bào)告
- 商業(yè)模式的設(shè)計(jì)與創(chuàng)新課件
- 創(chuàng)新者的窘境讀書課件
- 9001內(nèi)審員培訓(xùn)課件
- 人教版五年級(jí)上冊(cè)小數(shù)除法豎式計(jì)算練習(xí)練習(xí)300題及答案
- 綜合素質(zhì)提升培訓(xùn)全面提升個(gè)人綜合素質(zhì)
- 如何克服高中生的社交恐懼癥
- 聚焦任務(wù)的學(xué)習(xí)設(shè)計(jì)作業(yè)改革新視角
- 2024高二語文期末試卷(選必上、中)及詳細(xì)答案
- 淋巴瘤患者的護(hù)理
- 水利工程建設(shè)管理概述課件
- 人美版初中美術(shù)知識(shí)點(diǎn)匯總九年級(jí)全冊(cè)
評(píng)論
0/150
提交評(píng)論