用于多种单位转换的 C# 数据结构
我有一个 C# 应用程序,需要在 3 个不同的单位之间进行转换(例如:升、加仑和品脱)。
该应用程序需要了解特定体积的液体,例如:1 品脱、10 品脱、20 品脱和 100 品脱。 我打算进行计算并对值进行硬编码(不理想但必要),
我正在寻找一种数据结构,它允许我轻松地从一个单位转换为另一个单位。
有什么建议么?
请注意:我实际上并没有使用大量液体,这只是一个例子!
I have a C# app and I need to convert between 3 different units (say for example: litres, gallons, and pints).
The app needs to know about certain volumes of liquid, say: 1 pint, 10 pints, 20 pints and 100 pints. I intend to do the calculations and hard code the values (not ideal but necessary),
I'm looking for a data structure that will allow me to easily convert from one unit to another.
Any suggestions?
Please note: I'm not actually using volumes of liquid, its just an example!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以存储转换系数矩阵,其中
您有(不准确,但假设一升有两品脱,一加仑有 4 升)
或者,您可以决定在转换为另一种类型之前,所有内容都会转换为基值(升),那么您只需要第一行。
将其包装在一个方法中,该方法采用多个单位以及“from”类型和“two”类型进行转换。
希望这有助于
编辑:根据要求编写一些代码
You can store a matrix of conversion factors where
You'd have (not accurate, but assuming there are two pints to a litre and 4 litres to a gallon)
Alternatively, you can decide that everything is converted to a base value (litres) before being converted to another type, then you just need the first line.
Wrap this in a method that takes a number of units and "from" type and "two" type for the conversion.
Hope this helps
EDIT: some code, as requested
我通过提供正确的访问方法(属性)用另一种语言完成了此操作:
另一个优点是内部格式并不重要。
I have done this in an other language by providing the correct access methods (properties):
One additional advantage is that the internal format does not matter.
请查看显式接口实现,我认为它可以帮助你,样本就是你所需要的。
编辑:从 MSDN 复制的示例
Please take a look at Explicit Interface Implementation, I think it can help you, the sample is about what you need.
EDIT: sample copied from MSDN
如果有帮助,您可能需要使用在不同单位之间进行转换的 nuget 包:
UnitConversion on:
全面披露:我目前正在维护这个包。
In case it is helpfull, you might want to use a nuget package that's doing conversions between various units:
UnitConversion on:
Full disclosure: I'm currently maintaining this package.
以下是完整的源代码:
它以以下格式处理文件
并计算,例如,以十格勒为单位的 50 厘格勒。
该代码能够进行链式转换(例如年->日->小时->秒)。
Here's the source code in its full entirety:
It processes the file in the following format
and calculates, for instance, 50 centiglobs in decaglobs.
This code is capable of doing chained conversions (e.g. year -> day -> hour -> second).