Files
2025-03-13 12:04:22 -07:00

413 lines
13 KiB
C#

using System;
using System.Text;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
namespace Raytheon.Units
{
/// <summary>
/// This class represents a length.
///
/// It has no constructors. Instead, it provides multiple methods for creating objects of this
/// type. Those methods are of the form FromXXX, where XXX is a unit (e.g. FromMeters).
///
/// Properties (e.g. Meters) are provided to convert the value to other units and return
/// as type double.
///
/// Methods (operator overloads) are provided to perform calculations with related types (e.g.
/// Velocity).
/// </summary>
[Serializable]
[DataContract]
public class Length
{
public enum Unit
{
Meters,
Centimeters,
Millimeters,
Micrometers,
Nanometers,
Inches,
Feet
}
public static IDictionary<Unit, List<string>> UnitAbbreviations = new Dictionary<Unit, List<string>>()
{
{Unit.Meters, new List<string>(){ "m" } },
{Unit.Centimeters, new List<string>(){ "cm" } },
{Unit.Millimeters, new List<string>(){ "mm" } },
{Unit.Micrometers, new List<string>(){ "um" } },
{Unit.Nanometers, new List<string>(){ "nm" } },
{Unit.Inches, new List<string>(){ "in" } },
{Unit.Feet, new List<string>(){ "ft" } },
};
private const Unit DefaultUnits = Unit.Meters;
private const double FeetPerMeter = 3.280839895013123;
private const double InchesPerMeter = 12 * FeetPerMeter;
private const double MilesPerMeter = FeetPerMeter / 5280;
[DataMember(Name = "Length", IsRequired = true)]
private double _length; // meters
// map: unit => abbreviation, conversion method and property
private static IDictionary<Unit, UnitInfo<Length>> _unitInfo = new Dictionary<Unit, UnitInfo<Length>>()
{
{ Unit.Meters, new UnitInfo<Length>(UnitAbbreviations[Unit.Meters], FromMeters, typeof(Length).GetProperty("Meters").GetGetMethod()) },
{ Unit.Centimeters, new UnitInfo<Length>(UnitAbbreviations[Unit.Centimeters], FromCentimeters, typeof(Length).GetProperty("Centimeters").GetGetMethod()) },
{ Unit.Millimeters, new UnitInfo<Length>(UnitAbbreviations[Unit.Millimeters], FromMillimeters, typeof(Length).GetProperty("Millimeters").GetGetMethod()) },
{ Unit.Micrometers, new UnitInfo<Length>(UnitAbbreviations[Unit.Micrometers], FromMicrometers, typeof(Length).GetProperty("Micrometers").GetGetMethod()) },
{ Unit.Nanometers, new UnitInfo<Length>(UnitAbbreviations[Unit.Nanometers], FromNanometers, typeof(Length).GetProperty("Nanometers").GetGetMethod()) },
{ Unit.Feet, new UnitInfo<Length>(UnitAbbreviations[Unit.Feet], FromFeet, typeof(Length).GetProperty("Feet").GetGetMethod()) },
{ Unit.Inches, new UnitInfo<Length>(UnitAbbreviations[Unit.Inches], FromInches, typeof(Length).GetProperty("Inches").GetGetMethod()) }
};
/// <summary>
/// Prevents a default instance of the <see cref="Length"/> class from being created.
/// Use FromXXX methods to create objects of this type.
/// </summary>
/// <exception cref="System.Exception">No one should be calling this, it is only here to prevent users from creating default object</exception>
private Length()
{
throw new InvalidOperationException("No one should be calling this, it is only here to prevent users from creating default object");
}
/// <summary>
/// ctor used by this class to create objects in FromXXX methods
/// </summary>
/// <param name="length">The length - meters</param>
private Length(double length)
{
_length = length;
}
#region conversion properties
public double Centimeters
{
get { return _length * 100; }
}
public double Feet
{
get { return _length * FeetPerMeter; }
}
public double Inches
{
get { return _length * InchesPerMeter; }
}
public double Meters
{
get { return _length; }
}
public double Micrometers
{
get { return _length * 1000000; }
}
public double Millimeters
{
get { return _length * 1000; }
}
public double Nanometers
{
get { return _length * 1000000000; }
}
#endregion
#region creation methods
public static Length FromCentimeters(double centimeters)
{
return new Length(centimeters / 100);
}
public static Length FromFeet(double feet)
{
return new Length(feet / FeetPerMeter);
}
public static Length FromInches(double inches)
{
return new Length(inches / InchesPerMeter);
}
public static Length FromMeters(double meters)
{
return new Length(meters);
}
public static Length FromMicrometers(double micrometers)
{
return new Length(micrometers / 1000000);
}
public static Length FromMillimeters(double millimeters)
{
return new Length(millimeters / 1000);
}
public static Length FromNanometers(double nanometers)
{
return new Length(nanometers / 1000000000);
}
#endregion
public override bool Equals(object obj)
{
Length l = obj as Length;
return (l == null) ? false : (this._length == l._length);
}
public override int GetHashCode()
{
return _length.GetHashCode();
}
#region binary operators
// not implementing %, &, |, ^, <<, >>
public static Length operator +(Length left, Length right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot add a null Length");
if (null == right)
throw new ArgumentNullException("right", "Cannot add null Length");
return new Length(left._length + right._length);
}
public static Length operator -(Length left, Length right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot subtract a null Length");
if (null == right)
throw new ArgumentNullException("right", "Cannot subtract a null Length");
return new Length(left._length - right._length);
}
public static Length operator *(Length length, double scalar)
{
if (null == length)
throw new ArgumentNullException("length", "Cannot multiply a null Length");
return new Length(length._length * scalar);
}
public static Length operator *(double scalar, Length length)
{
if (null == length)
throw new ArgumentNullException("length", "Cannot multiply a null Length");
return new Length(scalar * length._length);
}
public static Length operator /(Length length, double scalar)
{
if (null == length)
throw new ArgumentNullException("length", "Cannot divide a null Length");
if (0.0 == scalar)
throw new DivideByZeroException("Cannot divide Length by 0");
return new Length(length._length / scalar);
}
#endregion
#region comparison operators
public static bool operator ==(Length left, Length right)
{
bool bReturn = false;
if (object.ReferenceEquals(left, null))
{
if (object.ReferenceEquals(right, null))
{
//both are null, so we are ==
bReturn = true;
}
}
else
{
if (!object.ReferenceEquals(left, null) &&
!object.ReferenceEquals(right, null))
{
bReturn = left._length == right._length;
}
}
return bReturn;
}
public static bool operator !=(Length left, Length right)
{
return !(left == right);
}
public static bool operator <(Length left, Length right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null Length");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null Length");
return (left._length < right._length);
}
public static bool operator >(Length left, Length right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null Length");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null Length");
return (left._length > right._length);
}
public static bool operator <=(Length left, Length right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null Length");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null Length");
return (left._length <= right._length);
}
public static bool operator >=(Length left, Length right)
{
if (null == left)
throw new ArgumentNullException("left", "Cannot compare null Length");
if (null == right)
throw new ArgumentNullException("right", "Cannot compare null Length");
return (left._length >= right._length);
}
#endregion
#region operators with non-length classes
/// <summary>
/// Implements the operator / for Velocity = Length / PrecisionTimeSpan
/// </summary>
/// <param name="length">The length.</param>
/// <param name="time">The time.</param>
/// <returns>
/// Velocity
/// </returns>
public static Velocity operator /(Length length, PrecisionTimeSpan time)
//public static Velocity operator /(Length length, TimeSpan time)
{
if (null == length)
throw new ArgumentNullException("length", "Cannot divide a null Length");
if (null == time)
throw new ArgumentNullException("time", "Cannot divide by a null PrecisionTimeSpan");
if (0.0 == time.Milliseconds)
throw new DivideByZeroException("Cannot divide Length by 0 time");
return Velocity.FromMetersPerSec(length.Meters / time.Seconds);
}
/// <summary>
/// Implements the operator / for PrecisionTimeSpan = Length / Velocity
/// </summary>
/// <param name="length">The length.</param>
/// <param name="time">The velocity.</param>
/// <returns>
/// PrecisionTimeSpan
/// </returns>
public static PrecisionTimeSpan operator /(Length length, Velocity velocity)
{
if (null == length)
throw new ArgumentNullException("length", "Cannot divide a null Length");
if (null == velocity)
throw new ArgumentNullException("velocity", "Cannot divide by a null Velocity");
if (0.0 == velocity.MetersPerSec)
throw new DivideByZeroException("Cannot divide Length by 0 velocity");
return PrecisionTimeSpan.FromSeconds(length.Meters / velocity.MetersPerSec);
}
#endregion
#region parsing
public static Length Parse(string s)
{
return Common.Parse(s, _unitInfo);
}
public static bool TryParse(string s, out Length value)
{
try
{
value = Length.Parse(s);
return true;
}
catch (Exception)
{
value = null;
return false;
}
}
#endregion
/// <summary>
/// Returns a string appended with default units (e.g. "1.23 m/sec^2").
/// </summary>
/// <returns>
/// A string that represents this instance
/// </returns>
public override string ToString()
{
return ToString(DefaultUnits);
}
/// <summary>
/// overload that returns a string appended with specified units (e.g. "1.23 ft/sec^2").
/// </summary>
/// <param name="units"></param>
/// <returns></returns>
public string ToString(Unit units)
{
double value = (double)_unitInfo[units].PropertyGetter.Invoke(this, null);
return $"{value} {_unitInfo[units].Abbreviation[0]}";
}
}
}