zoukankan      html  css  js  c++  java
  • CLR via C#学习笔记:C#操作符重载学习( 基于.NET3.5 )

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication1
    {
        
    class MyCls
        
    {
            
    public int X
            
    {
                
    get;
                
    set;
            }

            
    public int Y
            
    {
                
    get;
                
    set;
            }

            
    public override string ToString()
            
    {
                
    return string.Format("X={0},Y={1}", X, Y);
            }

            
    public override bool Equals(object obj)
            
    {
                MyCls a 
    = obj as MyCls;

                
    return a.X == this.X && a.Y == this.Y;
            }

            
    public override int GetHashCode()
            
    {
                
    return X * Y;
            }
          
            
    public static MyCls operator +(MyCls a, MyCls b)
            
    {
                
    return new MyCls() { X = a.X + b.X, Y = a.Y + b.Y };
            }

            
    public static MyCls operator -(MyCls a, MyCls b)
            
    {
                
    return new MyCls { X = a.X - b.X, Y = a.Y - b.Y };
            }

            
    public static MyCls operator ++(MyCls a)
            
    {
                
    return new MyCls() { X = a.X++, Y = a.Y++ };
            }

            
    public static MyCls operator --(MyCls a)
            
    {
                
    return new MyCls() { X = a.X--, Y = a.Y-- };
            }

            
    public static bool operator ==(MyCls a, MyCls b)
            
    {
                
    return a.X == b.X && a.Y == b.Y;
            }

            
    public static bool operator !=(MyCls a, MyCls b)
            
    {
                
    return a.X != b.X && a.Y != b.Y;
            }

            
    public static void Main()
            
    {
                MyCls a 
    = new MyCls { X = 1, Y = 1 };
                MyCls b 
    = new MyCls { X = 2, Y = 2 };
                Console.WriteLine(a 
    + b);
                Console.WriteLine(b 
    - a);
                Console.WriteLine(b
    ++);
                Console.WriteLine(a
    --);
                Console.WriteLine(a
    ++ == b);
                Console.WriteLine(a
    != b--);
                Console.ReadLine();
            }

        }

    }


     

    输出结果:

    X=3,Y=3
    X=1,Y=1
    X=3,Y=3
    X=0,Y=0
    True
    False

  • 相关阅读:
    First Missing Positive
    Find Minimum in Rotated Sorted Array II
    switch两种写法对比
    常用的前端JavaScript方法封装
    如何保证缓存和数据库的一致性?
    14个前端小知识
    dataTable转换特定的类
    C# MD5 32大写位加密 UTF-8编码
    另一个 SqlParameterCollection 中已包含 SqlParameter
    C#实现数据回滚,A事件和B事件同时执行,其中任何一个事件执行失败,都会返回失败
  • 原文地址:https://www.cnblogs.com/rockniu/p/1206880.html
Copyright © 2011-2022 走看看