.NET - 为什么 C# 中没有定点数字数据类型?
看起来定点数据类型会有很多用途。为什么.NET 中没有一个?
注意:我知道我们可以创建自己的类/结构来满足我们的定点目的和需求。那不是我的问题。我想知道为什么 MS 决定不包含定点数字数据类型。
It seems like there would be a ton of uses for a fixed point data type. Why is there not one in .NET?
Note: I understand we can create our own classes/structs to suit our fixed point purposes and needs. That's not my question. I want to know WHY MS decided not to include a fixed point numeric data type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找鲜为人知的
System.Data.SqlTypes。 SqlDecimal
类。You're looking for the little-known
System.Data.SqlTypes.SqlDecimal
class.十进制
(以 10 为底的浮动点)被认为足够好。Decimal
(base-10 floating point) was deemed to be good enough.一个问题可能与以下问题有关:你在哪里解决这个问题? .NET 中的类型不能通过类型以外的其他参数进行参数化,因此
FixedNum<18,6>
根本不可能。并且您不想创建FixedNum1x0
、FixedNum1x1
、FixedNum2x0
、FixedNum2x1
、FixedNum2x2
> 等。您需要能够参数化您的定点类型,而不仅仅是值,因为这将导致几乎不可能跟踪错误:
因此,您每次获取定点值时都需要检查和约束它们不是局部变量的东西。当您想要固定的比例或精度时,就像使用
decimal
一样。换句话说,考虑到 .NET 类型系统的限制,
decimal
已经是上面的 FixNum 类的内置实现。One problem probably has to do with the question: where do you fix the point? A type in .NET cannot be parametrized by other arguments than types, so
FixedNum<18,6>
is simply not possible. And you do not want to createFixedNum1x0
,FixedNum1x1
,FixedNum2x0
,FixedNum2x1
,FixedNum2x2
, etc.You need to be able to parametrize your fixed point type, not just values, because that would lead to nigh impossible to track mistakes:
So you'd need to check and constrain your fixed point values every time you get them from something that's not a local variable. As you do with
decimal
when you want a fixed scale or precision.In other words, given the limitations of the .NET type system,
decimal
is already built-in implementation of the FixedNum class above.