Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically retrieve Type based on Unit #1336

Closed
mariuszhermansdorfer opened this issue Dec 8, 2023 · 4 comments
Closed

Automatically retrieve Type based on Unit #1336

mariuszhermansdorfer opened this issue Dec 8, 2023 · 4 comments

Comments

@mariuszhermansdorfer
Copy link

Is your feature request related to a problem? Please describe.

I'm working on UI elements (sliders, steppers, etc.), where users can define the unit type of each control at runtime.

Describe the solution you'd like

I'd like to automatically retrieve the type (Length, Angle, Scalar, etc.) based on the chosen unit LengthUnit.Meter, AngleUnit.Degree, etc.
I need this information to parse quantities from input strings:

            if (Quantity.TryParse(_type, "0.31 km", out IQuantity quantity))
                _displayText.Text = quantity.ToUnit(_unit).ToString();

Describe alternatives you've considered

My current workaround is based on manipulating strings:

            var typeName = _unit.GetType().Name;
            typeName = typeName.Remove(typeName.Length - "Unit".Length);
            _type = Type.GetType($"UnitsNet.{typeName}, UnitsNet");
@angularsen
Copy link
Owner

angularsen commented Dec 8, 2023

Hi, it's not super straight forward to discover, but you can do it like this:

Enum unit = LengthUnit.Centimeter;
Type quantityType = Quantity.From(1, unit).GetType();


// 10 cm
IQuantity q = Quantity.Parse(quantityType, "100 mm").ToUnit(unit);

@angularsen
Copy link
Owner

angularsen commented Dec 8, 2023

Something we could add that maybe would make this a bit more discoverable:

UnitInfo unitInfo = Quantity.GetUnitInfo(LengthUnit.Centimeter);

Type quantityType1 = Quantity.ByName[unitInfo.QuantityName].Type; // Add new Type property on QuantityInfo
Type quantityType2 = unitInfo.QuantityInfo.Type; // Also add new QuantityInfo property on UnitInfo

@mariuszhermansdorfer
Copy link
Author

Thanks for a prompt response @angularsen!

The workaround you suggested works very well!

@angularsen
Copy link
Owner

Glad to hear it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants