听起来您应该使用 结构 而不是类…,然后创建隐式转换运算符,以及用于加法的各种运算符等。
这是一些示例代码:
public struct VeLocity
{
private readonly double value;
public VeLocity(double value)
{
this.value = value;
}
public static implicit operator VeLocity(double value)
{
return new VeLocity(value);
}
public static VeLocity operator +(VeLocity first, VeLocity second)
{
return new VeLocity(first.value + second.value);
}
public static VeLocity operator -(VeLocity first, VeLocity second)
{
return new VeLocity(first.value - second.value);
}
// TODO: Overload == and !=, implement IEquatable<T>, override
// Equals(object), GetHashCode and ToStrin
}
class Test
{
static void Main()
{
VeLocity ms = 0;
ms = 17.4;
// The statement below will perform a conversion of 9.8 to VeLocity,
// then call +(VeLocity, VeLocity)
ms += 9.8;
}
}
(作为一个旁注…我看不出它是如何真正代表速度的,因为肯定需要方向和幅度。)