Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Ví dụ về quá tải toán tử trong C#: Quote: 1: public class zzz 2: { 3: public static void Main() 4: { 5: yyy a = new yyy(10); 6: yyy b = new yyy(5); 7: yyy c; 8: c = a + b ; 9: System.Console.WriteLine(c.i); 10: } 11: } 12: 13: public class yyy 14: { 15: public int i; 16: public yyy(int j) 17: { 18: i = j; 19: } 20: 21 | Ví dụ về quá tải toán tử trong C Quote 1 public class zzz 2 3 public static void Main 4 5 yyy a new yyy 10 6 yyy b new yyy 5 7 yyy c 8 c a b 9 System.Console.WriteLine c.i 10 11 12 13 public class yyy 14 15 public int i 16 public yyy int j 17 18 i j 19 20 21 public static yyy operator yyy x yyy y 22 23 System.Console.WriteLine x.i 24 yyy z new yyy 12 25 return z 26 27 Mặc dù chúng ta viết mã trong C có quá tải toán tử như vậy nhưng trình biên dịch C sẽ phải dịch ra ngôn ngữ trung gian IL để thực thi trên môi trường .NET. Đoạn lệnh đã được biên dịch ra như sau Quote 1 .assembly my_namespace 2 .class private auto ansi zzz extends mscorlib System.Object 3 4 .method public hidebysig static void vijay il managed 5 6 .entrypoint 7 .locals class yyy V_0 class yyy V_1 class yyy V_2 8 ldc.i4.s 10 9 newobj instance void yyy .ctor int32 10 stloc.0 11 ldc.i4.5 12 newobj instance void yyy .ctor int32 13 stloc.1 14 ldloc.0 15 ldloc.1 16 call class yyy yyy op_Addition class yyy class yyy 17 stloc.2 18 ldloc.2 19 ldfld int32 yyy i 20 call void mscorlib System.Console WriteLine int32 21 ret 22 ret 23 24 25 26 .class public auto ansi yyy extends mscorlib System.Object 27 28 .field public int32 i 29 .method public hidebysig specialname static class yyy op_Addition class yyy x class yyy y il managed 30 31 .locals class yyy V_0 class yyy V_1 32 ldarg.0 33 ldfld int32 yyy i 34 call void mscorlib System.Console WriteLine int32 35 ldc.i4.s 12 36 newobj instance void yyy .ctor int32 37 stloc.0 38 ldloc.0 39 stloc.1 40 ldloc.1 41 ret 42 43 44 .method public hidebysig specialname rtspecialname instance void .ctor int32 j il managed 45 46 ldarg.0 47 call instance void mscorlib System.Object .ctor 48 ldarg.0 49 ldarg.1 50 stfld int32 yyy i 51 ret 52 53 Nortonxe UDS