Parsing quantity strings for custom units #1263
-
Hello, Currently I'm trying to create my custom unit to be able to parse a quantity string into an actual quantity. And looks like I couldn't find a way to do the latter. I've added my custom IQuantity and Enum:
Also, I've added some abbreviations:
And now I want to parse a string like "6 items" to an Item object. The documentation clearly states, "Reuse QuantityParser and UnitParser to parse quantity strings like "5 cm" and "cm" for your own quantities and units", so this should definitely be possible. But there's no code sample for this exact case there. The usual way of using UnitsNet.Quantity.TryParse() doesn't work, because inside the TryParse method there's an explicit check if the passed type belongs to one of the types known to UnitsNet, so the custom one gets false:
I've browsed through the code and the unit tests and found exactly what I need:
Alas, the QuantityParser class is internal, so I cannot use it directly. Also, there's the UnitParser class which is public, but it seems to be only capable of parsing an abbreviation (e.g., "foo") to enum, which is not exactly what I need. I have a feeling that I'm missing something simple. Could you please help me guys? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hi, sorry for the confusion. Custom units are quite experimental still, and has its rough edges.
Nuget should be out shortly. |
Beta Was this translation helpful? Give feedback.
-
You really made an effort to figure this out before asking too, I appreciate that 🙇 |
Beta Was this translation helpful? Give feedback.
Hi, sorry for the confusion. Custom units are quite experimental still, and has its rough edges.
QuantityParser
was intended to be public eventually, but I guess that was forgotten.I merged a fix now, let me know how this works out for you.
#1264
Nuget should be out shortly.
Release UnitsNet/5.20.0 · angularsen/UnitsNet