运算符重载

    public class Program
    {
        
public override bool Equals(object obj)
        {
            
if (obj == null)
                
return false;
            
if (object.ReferenceEquals(obj, this))
                
return true;
            
if (this.GetType() != obj.GetType())
                
return false;
            
//
            
//TODO:userdefined compare.
            
//
            return base.Equals(obj);//its base class is not object or valuetypeclss
        }
        
public static void Main()
        {
            Vector v1 
= new Vector(123);
            Vector v2 
= new Vector(123);
            Vector v3 
= v1 + v2;
            Console.Write(v3.ToString());
            Console.Read();
        }
    }
    
public 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 v)
        {
            
this.x = v.x;
            
this.y = v.y;
            
this.z = v.z;
        }
        
public override string ToString()
        {
            
return string.Format("x:{0},y:{1},z{2}", x, y, z);
        }
        
public static Vector operator +(Vector v1, Vector v2)
        {
            Vector v 
= new Vector(v1);
            v.x 
+= v2.x;
            v.y 
+= v2.y;
            v.z 
+= v2.z;
            
return v;
        }
    }
posted @ 2009-01-06 11:53  roboth  阅读(264)  评论(0)    收藏  举报