您当然不能创建派生自 的类型decimal
,因为它是一个结构 - 并且您不能创建结构的子类型。
不过,您可以创建自己的包含小数的Currency
结构。您希望重载所有算术运算符,以基本上对包含的十进制值执行算术,然后适当地四舍五入。
例如:
public struct Currency
{
private readonly decimal value;
public Currency(decimal value)
{
this.value = decimal.Round(value, 2);
}
public override string ToString()
{
return value.ToString();
}
public static Currency operator+(Currency left, Currency right)
{
return new Currency(left.value + right.value);
}
public static Currency operator-(Currency left, Currency right)
{
return new Currency(left.value - right.value);
}
public static Currency operator/(Currency left, int right)
{
return new Currency(left.value / right);
}
}
class Test
{
static void Main()
{
Currency currency = new Currency(15);
Console.WriteLine(currency / 10); // Prints 1.5
Console.WriteLine(currency / 100); // Prints 0.15
Console.WriteLine(currency / 1000); // Prints 0.2
}
}
(显然这里还有很多需要 - 特别是您需要覆盖GetHashCode
and Equals
,实现IEquatable<T>
等)
这绝对是你想要的吗?我认为在中间操作期间保持尽可能高的精度更为常见,并且仅在最后一刻进行,例如存储在数据库中或显示给用户。