# 帮帮我，我负载过重

Eric Gunnerson
Microsoft Corporation
2001年6月21日

int i = 5;
int sum = i + j;


Complex i = 5;
Complex sum = i + j;


Complex i = new Complex(5);


## 任何事情都有特定的时间和场所

### 测验

#### 1

BigNum n1 = new BigNum("123456789012345");
BigNum n2 = new BigNum("11111");
BigNum sum = n1 + n2;


#### B

Matrix m1 = loadMatrix();
Matrix result = m1 * m2;


#### iii

DBRow row = query.Execute();
while (!row.Done)
{
row++;
}


#### IV

Account current = findAccount(idNum);
current += 5;


### 答案和讨论

#### iii

DBRow row = query.Execute();
while (!row.MoveNext())
{
}


## 重载算术运算符

struct Vector
{
float x;
float y;

public Vector(float x, float y)
{
this.x = x;
this.y = y;
}
}


1. 获取长度
2. 将矢量乘以某个数字
3. 将矢量除以某个数字
4. 将两个矢量相加
5. 将一个矢量减去另一个矢量
6. 计算两个矢量的点积

### 长度

   public float Length
{
get
{
return((float) Math.Sqrt(x * x + y * y));
}
}


### 将矢量乘以/除以某个数字

   public static Vector operator*(Vector vector, float multiplier)
{
return(new Vector(vector.x * multiplier,
vector.y * multiplier));
}


### 将两个矢量进行加减

   public static Vector operator+(Vector vector1, Vector vector2)
{
return(new Vector(vector1.x + vector2.x,
vector1.y + vector2.y));
}


### 计算点积

   double v1i = (velocity * center) / (t * t);
double v1i = Vector.DotProduct(velocity, center) / (t * t);
double v1i = velocity.DotProduct(center) / (t * t);


   public static double DotProduct(Vector v1, Vector v2)
{
return(v1.x * v2.x + v1.y * v2.y);
}


## 重载的转换

Complex i = 5;
Complex sum = i + j;


### 隐式和显式转换

C# 同时支持隐式和显式转换。隐式转换是那些总是能成功执行的转换，并且其成功的原因通常是目标类型的范围等于或大于源类型的范围。从 short 到 int 的转换就是一个隐式转换。隐式转换可以作为赋值语句的一部分：

   short svalue = 5;
long lvalue = svalue;


   long lvalue = 5;
short svalue = (short) lvalue;


   public static implicit operator Complex(int value)
{
return(new Complex(value, 1.0));
}


## 网站收集袋

http://www.cshrp.net/

0 0